[英]Typing in Typescript
我有一個名為param的參數的函數,如下所示:
function x(param: One | Two) {
//do something
}
interface One {
value: IValue,
name: string,
id: number
}
interface Two {
value: IValue2,
name: string,
id: number,
selected: boolean
}
我可以使用相同的參數,兩個不同的接口嗎? 謝謝!
您可以,並且您的參數語法正確! 作為參考,TypeScript將其稱為聯合類型 。
使用它們的主要警告是,您只能訪問所有類型的公共成員 - 例如,您的接口都包含name
, value
和id
,因此您可以在函數中使用它們。 但是,只有interfaceTwo
具有selected
成員,因此無法使用。
順便說一句,我不知道這個例子是你剛剛輸入的東西,所以你可能已經知道這一點,但你的接口沒有正確定義 - 你需要使用interface
關鍵字並結束行分號。 給類型TitleCase
名稱也是一種約定:
function x(param: InterfaceOne | InterfaceTwo){
console.log(param.name); // Valid!
console.log(param.id); // Valid!
console.log(param.value); // Valid - but has the type IValue | IValue2,
// so you can only access the common fields
// of those types!
console.log(param.selected); // INVALID - InterfaceOne doesn't have a selected member
}
interface InterfaceOne {
value: IValue;
name: string;
id: number;
}
interface InterfaceTwo {
value: IValue2;
name: string;
id: number;
selected: boolean;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.