在Typescript中使用'--strictFunctionTypes'有什么好处? [英] What is the benefit of using '--strictFunctionTypes' in Typescript?
问题描述
据我了解,Typescript中的--strictFunctionTypes
编译器选项阻止了一种非常常见的多态用例的工作:
As I understand it, --strictFunctionTypes
compiler option in Typescript prevents a very common use case of polymorphism from working:
type Handler = (request: Request) => Response
const myHandler: Handler = (request: Request & { extraArg: boolean }) => {
return !!request.extraArg
}
通常,我认为strict
系列中的所有编译器选项都有一些好处,但是在这种情况下,我所看到的是它阻止了非常逻辑的行为.
Generally, I assume that all compiler options in the strict
family have some great benefits, but in this case, all I see is that it prevents a very logical behavior from working.
那么在什么情况下此选项实际上可以带来一些好处?它可以防止哪些有害情况?
So what are the cases where this option actually gives some benefits? Which harmful scenarios does it prevent?
推荐答案
在没有strictFunctionTypes
的情况下,导致运行时错误实际上非常容易.
It's actually very easy to cause a runtime error without 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
因此,在上面的示例中,函数签名需要一个Request
,这就是我们必须传递的所有Request
.但是该实现期望接收其中需要extraArg
的Request & { extraArg: string }
,并且无需进行检查即可访问它(毕竟,如果需要的话,被调用者应该将其传递进来).
So in the above example, the function signature requires a Request
so that is all we have to pass in a Request
. But the implementation expects to receive Request & { extraArg: string }
in which extraArg
is required, and access it without having to do a check (after all if it's required the called should have passed it in).
这是strictFunctionTypes
防止的错误类型.如果签名中的参数是基本类型,而实现需要一个派生类型,则不能保证实现将接收到派生类型,因为签名仅要求将基本类型传入
This is the kind of errors strictFunctionTypes
prevents. If an argument in the signature is of a base type, while the implementation expects a derived type, there is no guarantee that the implementation will receive the derived type, as the signature only requires the base type to be passed in
这篇关于在Typescript中使用'--strictFunctionTypes'有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!