typescript - 在 Typescript 中使用“--strictFunctionTypes”有什么好处?
问题描述
据我了解,--strictFunctionTypes
Typescript 中的编译器选项阻止了一个非常常见的多态性用例:
type Handler = (request: Request) => Response
const myHandler: Handler = (request: Request & { extraArg: boolean }) => {
return !!request.extraArg
}
通常,我假设该strict
系列中的所有编译器选项都有一些很大的好处,但在这种情况下,我所看到的只是它阻止了非常合乎逻辑的行为。
那么在哪些情况下这个选项实际上会带来一些好处呢?它防止了哪些有害情况?
解决方案
没有strictFunctionTypes
.
让我们考虑以下示例:
type Handler = (request: Request) => Response
const myHandler: Handler = (request: Request & { extraArg: string }) => {
// extraArg is required so need to check for null
request.extraArg.toUpperCase();
return null as any;
}
declare let r: Request; // comes from sowhere
myHandler(r); // no need to pass in the extraArg not required by the signature
所以在上面的例子中,函数签名需要 aRequest
所以我们只需要传入 a Request
。但是实现期望接收需要Request & { extraArg: string }
的内容extraArg
,并在无需检查的情况下访问它(毕竟,如果需要,被调用者应该将其传入)。
这是strictFunctionTypes
防止错误的类型。如果签名中的参数是基类型,而实现需要派生类型,则无法保证实现将接收派生类型,因为签名只需要传入基类型
推荐阅读
- python - 如何使用 FloatRangeSlider 作为绘图的 X 轴范围
- html - 移动设备上的 Bootstrap Dropdown 左/右位置错误
- ios - 如何在 func 中使用转义闭包返回一些数据?
- git - GitVersion 配置斗争以及如何在补丁后追加一个版本
- windows - 无法弄清楚如何使用 ffi 在 Dart 中使用 SetWindowsHookEx
- reactjs - babel core 7.4.4,默认使用所有 polyfill
- botframework - MS Teams Bot App - 如何使用按钮显示主菜单?
- css - 想要在语义 UI 中使用引导图标
- c++ - 致命错误:comdef.h:没有这样的文件或目录
- java - 使用来自 GraalVM 的 native-image 的 Java 调用 C 库