TypeScript 中的 strictBindCallApply
说明 strictBindCallApply 为什么会严格检查函数的 bind、call、apply 参数和返回值,以及它如何减少这些反射式调用的 any 泄漏。
#tech / dev
#resource / typescript
#type / concept
#status / growing
[!info] related notes
- 所属 MOC: TypeScript MOC
- 配置入口: tsconfig 使用详解
- 并列概念: TypeScript 中的 strict, TypeScript 类型检查
TypeScript 中的 strictBindCallApply
一句话定义
strictBindCallApply 会严格检查函数的 bind、call、apply 是否以正确参数被调用。
核心机制 / 工作原理
官方文档的例子是:
function fn(x: string) {
return parseInt(x);
}
const n1 = fn.call(undefined, "10");
const n2 = fn.call(undefined, false);
在这个选项开启时,第二行会报错,因为:
false不是string
而关闭时,这类调用可能被放过,甚至返回值直接退化成 any。
最小例子 / 最小场景
{
"compilerOptions": {
"strictBindCallApply": true
}
}
它的价值主要在:
- 依赖
call/apply的工具函数 - 元编程或函数式工具链
- 希望避免这类反射式调用把
any带进来的项目
边界与易混淆点
它不是普通函数调用检查
普通函数本来就会按签名检查。
这个选项专门针对的是:
bindcallapply
它既限制参数,也避免返回值退化成 any
官方文档明确写到,不开时这些方法可以接受任意参数并返回 any。
它属于 strict family
TSConfig 参考页当前写明:
trueifstrict;falseotherwise
参考信息
- TSConfig
strictBindCallApply: https://www.typescriptlang.org/tsconfig/strictBindCallApply.html - TSConfig Reference: https://www.typescriptlang.org/tsconfig/