问题
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
}
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?
回答1:
It's actually very easy to cause a runtime error without strictFunctionTypes
.
Let's consider the following example:
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
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).
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
来源:https://stackoverflow.com/questions/51767338/what-is-the-benefit-of-using-strictfunctiontypes-in-typescript