我正在瀏覽打字稿手冊中的一個示例,即使啟用了 stricNullChecks,我的函式也會回傳未定義。感覺編譯的時候應該報錯,但是這個編譯沒有問題,函式回傳undefined。
編碼 :
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
}
}
let mysquare: Shape = {kind: 'square', sideLength: 10}
console.log(getArea(mysquare))
我的 tsconfig :
{
"extends": "@tsconfig/node16/tsconfig.json",
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"sourceMap": true,
"types": ["node"],
"lib": [
"dom"
]
},
"exclude": [
"node_modules"
]
}
我的 package.json:
{
"devDependencies": {
"@tsconfig/node16": "^1.0.3",
"@types/node": "^18.7.23"
}
}
也許我在我的環境中使用 typescript,或者它應該回傳 undefined 而我在這里沒有得到東西?
uj5u.com熱心網友回復:
你還需要noImplicitReturns:
啟用后,TypeScript 將檢查函式中的所有代碼路徑以確保它們回傳值。
開啟它后,您將看到 的錯誤getArea,正如您所希望的那樣:
函式getArea(形狀:形狀):數字| 不明確的
并非所有代碼路徑都回傳值。(7030)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510425.html
標籤:打字稿
