使用 TypeScript 時,我意識到我并不完全了解屬性檢查的作業原理。在下面的示例中,我不明白為什么檢查.bold有效但檢查.type無效。
type CustomText = {
bold: boolean;
};
type TitleElement = { type: 'title'; children: string };
type Element = TitleElement | CustomText;
const el: Element = {
bold: true,
}
if (!el.bold) {
console.log("does not have bold")
}
if (!el.type) { // <- compiler error
console.log("does not have type")
}
uj5u.com熱心網友回復:
看起來,Typescript 已經知道您輸入的元素是什么型別(CustomText),因為它是在您的代碼中靜態分配的。如果它是動態的,TS 會為兩者抱怨。
例如:
const getElem = () => {
if(Math.floor((Math.random() * 10) 1)%2)
{
const x : TitleElement = { name: 'title', children: 'x' };
return x;
}
else{
const x : CustomText = { bold: false };
return x;
}
}
type CustomText = {
bold: boolean;
};
type TitleElement = { name: 'title'; children: string };
type Element2 = TitleElement | CustomText;
let el: Element2 = getElem();
if (!el.bold) {
console.log("does not have bold")
}
if (!el.name) { // <- compiler error
console.log("does not have type")
}
操場
聯合的目的是它允許所有聯合參與者的屬性。您可以輕松訪問和中存在的 任何屬性。TS 應該拋出一個錯誤,它會。如果您執行以下操作,TS 將在兩個 if 條件中引發錯誤。CustomTextTitleElement
type CustomText = {
bold: boolean;
both : string;
};
type TitleElement = { name: 'title'; children: string, both : string; };
type Element2 = TitleElement | CustomText;
const el: Element2 = {
bold: true,children: 'sing'
}
if (!el.bold) {
console.log("does not have bold")
}
if (!el.name) { // <- compiler error
console.log("does not have type")
}
if (!el.both) { // <- compiler error
console.log("does not have type")
}
發生這種情況是因為現在 TS 再次不確定 的型別,Element2并且它不能允許您訪問兩者中都不存在的屬性。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436893.html
標籤:打字稿
