2016-06-10 136 views
3

我有功能與參數命名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 
} 

我可以使用相同的參數,兩個不同的接口?謝謝!

回答

4

你可以,你的參數語法正確!作爲參考,TypeScript將其稱爲union type

主要告誡使用它們的是,你只能訪問成員共同所有的類型 - 例如,你都含有接口namevalueid,這樣你就可以在你的函數中使用這些。但是,只有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; 
} 
+1

如果在某些時候,你會想用param.selected屬性,你可以定義和使用類型保護功能:功能isInterfaceTwo(PARAM):參數是InterfaceTwo {...}。更多關於[這裏](https://blogs.msdn.microsoft.com/typescript/2015/09/16/announcing-typescript-1-6/) – baryo

+1

@baryo:是的,我真的沒有資格詳細介紹保鏢類型,因爲我從來沒有使用過它們,但他們肯定聽起來像是可以在這種情況下有所幫助! –