[英]Typescript type assertion doesn't work when field object is asserted in the function
我正在嘗試在 function 中的 object 字段上使用類型斷言,然后使用返回 object (在函數中斷言)。
這里有一個例子:
interface MyInterface {
abc: string;
}
type Abc = "A" | "B";
function assertAbc(v: string): asserts v is Abc {
if (!["A", "B"].includes(v)) {
throw Error();
}
};
const needAbc = (_: Abc) => true;
const shouldBeWithAbcType = () => {
const myObj: MyInterface = { abc: "A" };
// Everything that come after this should be an object with abc as type
assertAbc(myObj.abc);
// this work as intended, abc is of type Abc
needAbc(myObj.abc);
// Return the object
return myObj;
}
const c = shouldBeWithAbcType();
// c.abc is a string, so this doesn't work, why ?
needAbc(c.abc);
為什么needAbc(c.abc)
不起作用?
帶有示例的 ts 操場here
相同的示例但沒有 object(返回 Abc 類型)雖然有效。
您可以使用Type Guards 。 我認為asserts
關鍵字是多余的。 此外,類型保護 function 必須返回boolean
指示輸入是否屬於您期望的類型。
function isAbc(v: string): v is Abc {
if (!["A", "B"].includes(v)) {
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.