嘿伙計們,我想知道是否有正確的方法來做到這一點。我目前正在嘗試根據條件邏輯定義一種變數,但目前遇到了問題。Interface1 和 Interface2 在 Typescript 中都被定義為介面。使用 eventProps 變數型別的第一個 console.log 我得到一個 undefined 我以為我最初會注銷型別:'Interface1 | 介面2'。使用第二個 console.log 我注銷的是object型別,我認為它會注銷“Interface1”或“Interface2”。我做錯了什么/有沒有更好的方法來做我想要完成的事情?
let eventProps: Interface1 | Interface2;
console.log(typeof eventProps);
switch (event) {
case 'event1':
eventProps = { isCorrect: true, name: 'Mike' } as Interface1;
default:
eventProps = { isCorrect: true } as Interface2;
}
console.log(typeof eventProps);
uj5u.com熱心網友回復:
當您撰寫 Typescript 代碼時,它會被編譯為 Javascript,并且型別注釋和檢查將被清除。
typeof 是一個 Javascript 運算子,它只報告物件是什么原始型別,因此它按預期作業。
如果您使用命名類或原型,console.log將包括型別名稱。您可以使用instanceof它在運行時進行測驗:
class ConcreteType1 implements Interface1 {
isCorrect: boolean;
name: string;
constructor(isCorrect: boolean, name: string) {
this.isCorrect = isCorrect;
this.name = name;
}
}
const x:ConcreteType1 = getAConcreteType1();
console.log(x) // includes 'ConcreteType1'
if (x instanceof ConcreteType1) {
// typescript lets you use Interface1 fields in here
}
但是在運行時處理型別形狀和介面的最好、最慣用的方法是使用區分聯合。
只需添加一個公共欄位,在此示例中為“type”,該欄位設定為字串文字。然后,如果eventProps是聯合型,eventProps.type為'interface1' | 'interface2'使在運行測驗和易于縮小型。
interface Interface1 {
type: 'interface1';
/* some fields */
};
interface Interface2 {
type: 'interface2';
/* some fields */
}
const x: Interface1 | Interface2 = getOne();
console.log(x) // includes { type: 'interface1', ... } so you can tell
if (x.type === 'interface1') {
// typescript lets you use Interface1 fields in here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370698.html
標籤:打字稿
上一篇:有人知道如何輸入useRef嗎?
下一篇:Vue型別不存在屬性
