TypeScript 中的 strictFunctionTypes
说明 strictFunctionTypes 为什么会更严格地检查函数参数位置的兼容性,以及它为何主要作用于函数语法而不是方法语法。
#tech / dev
#resource / typescript
#type / concept
#status / growing
[!info] related notes
- 所属 MOC: TypeScript MOC
- 配置入口: tsconfig 使用详解
- 并列概念: TypeScript 中的 strict, TypeScript 类型检查
TypeScript 中的 strictFunctionTypes
一句话定义
strictFunctionTypes 会更严格地检查函数类型之间的参数兼容性,避免不安全的函数赋值通过类型检查。
核心机制 / 工作原理
官方文档的典型例子是:
function fn(x: string) {
console.log("Hello, " + x.toLowerCase());
}
type StringOrNumberFunc = (ns: string | number) => void;
let func: StringOrNumberFunc = fn;
如果不开这个选项,上面这种赋值可能被接受,但真正调用:
func(10);
就会在运行时崩。
开启 strictFunctionTypes 后,TypeScript 会在赋值阶段就阻止这种不安全兼容。
最小例子 / 最小场景
{
"compilerOptions": {
"strictFunctionTypes": true
}
}
它特别有价值的地方在于:
- 回调类型
- 高阶函数
- 事件处理器签名
- API 接口函数兼容判断
边界与易混淆点
它主要作用于函数语法
官方文档和 TS 2.6 release notes 都明确说明:
- 它主要检查 function syntax
- method syntax 和 constructor declarations 不在同样的严格度下
它修的是“函数参数双变性过宽”的老问题
更直白地说,它让“能不能把更窄参数函数塞给更宽参数函数类型”这件事更安全。
它通常也跟着 strict 一起开
TS 2.6 release notes 明确说:
- 它属于 strict family
参考信息
- TSConfig
strictFunctionTypes: https://www.typescriptlang.org/tsconfig/strictFunctionTypes.html - TypeScript 2.6 Release Notes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html