簡體   English   中英

Function 分配函數時未正確檢查參數類型

[英]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)

看起來當一個 function 被分配給另一個變量(或者我猜是作為參數傳遞)時,TypeScript 只檢查類型是否“單向兼容”(arguments 中的一個可以分配給另一個),但不會麻煩檢查參數類型兼容的方向是否與 function 分配的方向相匹配。

總是這樣嗎? 還是可以切換的編譯器選項?

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就會被包含進來,你就會得到一個編譯錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM