首页 > 解决方案 > 在 Typescript 中使用“--strictFunctionTypes”有什么好处?

问题描述

据我了解,--strictFunctionTypesTypescript 中的编译器选项阻止了一个非常常见的多态性用例:

type Handler = (request: Request) => Response

const myHandler: Handler = (request: Request & { extraArg: boolean }) => {
  return !!request.extraArg
}

通常,我假设该strict系列中的所有编译器选项都有一些很大的好处,但在这种情况下,我所看到的只是它阻止了非常合乎逻辑的行为。

那么在哪些情况下这个选项实际上会带来一些好处呢?它防止了哪些有害情况?

标签: typescriptinterfacestrictcompiler-options

解决方案


没有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防止错误的类型。如果签名中的参数是基类型,而实现需要派生类型,则无法保证实现将接收派生类型,因为签名只需要传入基类型


推荐阅读