三块面板:TS 源码 / 写死的 tsc 报错样本(非现场运行)/ 可点跑的等价 JS。看参数个数、重载对外签名、函数类型表达式。
function greet(name: string, title?: string) {
return title ? `${title} ${name}` : name
}
greet('阿蓝') // ✓ title 省略,为 undefined
greet('阿蓝', '先生') // ✓
greet() // ✗ 缺少必选参数 name
name 无 ? 也无默认值,是必选参数;title? 可选。编译器数出「1~2 个」,传 0 个越界。type Comparator = (a: string, b: string) => number
function sortBy(arr: string[], cmp: Comparator) {
return [...arr].sort(cmp)
}
const byLen: Comparator = (a, b) => a.length - b.length // a/b 由类型自动推断
function pick(x: string): string
function pick(x: number): number
function pick(x: string | number): string | number {
return x // 实现签名必须兼容所有对外签名
}
pick('a') // 返回类型是 string
pick(1) // 返回类型是 number
void 与 undefined 作返回类型的差别type IgnoreFn = () => void // 调用方不关心返回值:实现可返回任何东西
type StrictFn = () => undefined // 严格要求真的只返回 undefined
const ignore: IgnoreFn = () => 42 // ✓ 合法:void 承诺“我不读返回值”
const strict: StrictFn = () => 42 // ✗ 报错:必须是 undefined
() => void 是「别指望读返回值」的宽容约定(forEach 的回调就是它),TS 允许返回任意值;() => undefined 才严格要求只返回 undefined。想表达“随便返回但我不看”用 void。