分配函数时未正确检查函数参数类型

Function argument types are not properly check when assigning functions

我 运行 在 TypeScript 中遇到了一个奇怪的交互:

type Vector2 = { x: number; y: number };
type Vector3 = { x: number; y: number; z: number };

type Takes2 = (vec: Vector2) => void;
type Takes3 = (vec: Vector3) => void;

let f2: Takes2 = (vec) => console.log(vec.x + vec.y);
let f3: Takes3 = (vec) => console.log(vec.x + vec.y + vec.z);

// This makes sence - we call f2 with Vector3, so the "z" prop is going to be ignored
f3 = f2;
f3({ x: 1, y: 2, z: 5 }); // prints 3 (1 + 2)

// This makes no sence - we call f3 with Vector2, so we read undefined when we read vec.z
f2 = f3;
f2({ x: 1, y: 2 }); // prints NaN! (1 + 2 + undefined)

看起来当一个函数被分配给另一个变量时(或者我猜是作为参数传递),TypeScript 只检查类型是否“单向兼容”(一个参数可以分配给另一个) , 但不去检查参数类型兼容的方向是否与函数赋值的方向相匹配。

一直都是这样吗?或者是可以切换的编译器选项?

TypeScript 版本:4.4.4 tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "downlevelIteration": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    // "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    // "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    // "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": ".",
    "paths": {
      "*": ["./src/*"]
    }
  },
  "types": ["forge-viewer"],
  "include": ["src"]
}

您要找的标志是strictFunctionTypes

我在您的配置中注意到您已注释掉 "strict": true。如果你开启了严格模式(推荐),那么 strictFunctionTypes 就会被包含进来,你就会得到一个编译错误。