2017-06-01 33 views
1

我正在寫的class的許多方法暗含有相同的function type。我想要做的就是執行這個函數類型,以便我可以明確地聲明某些方法必須符合函數類型。如何在打字稿的類方法上強制實現函數類型接口?

例如

interface MyFunctionType {(resource: string | Resource): Something} 

和我的類有一些方法符合這個接口。

class MyClass { 
    // ... 

    someMethod() { /*...*/ } 

    someMethodThatConforms(resource: string | Resource) { 
     // ... 
     return new Something(/*...*/); 
    } 

    anotherMethodThatConforms(resource: string | Resource) { 
     // ... 
     return new Something(/*...*/); 
    } 

    someOtherMethod() { /*...*/ } 

    // ... 
} 

我知道someMethodThatConformsanotherMethodThatConforms符合接口,但現在我想知道我怎麼斷言someMethodThatConformsanotherMethodThatConforms必須符合接口MyFunctionType(這樣,如果我改變,MyFunctionType錯誤拋出) ?

回答

1

我們可以定義另一個接口,並有MyClass實現它:

interface MyFunctionType {(resource: string | Resource): Something} 

interface FixedMethods { 
    someMethodThatConforms: MyFunctionType; 
    // you can add more 
} 

class MyClass implements FixedMethods { 
    someMethodThatConforms(resource: string | Resource) { 
     // this method will fail type check, until we return a Something 
     return 1; 
    } 
} 

一個更復雜的方法:使用mapped type創建一個通用的類型:

interface MyFunctionType { (resource: string | Resource): Something } 

// a Mapped Type to fix methods, used in place of a interface 
type FixedMethods<T extends string> = { 
    [k in T]: MyFunctionType 
} 

class MyClass implements FixedMethods<"someMethodThatConforms" | "anotherMethodThatConforms"> { 
    someMethodThatConforms(resource: string | Resource) { 
     // this method will fail type check, until we return a Something 
     return 1; 
    } 

    // it also complains about lack of "anotherMethodThatConforms" method 
} 
+0

感謝你這樣做,這絕對是訣竅,但你知道如果有一種方法來做到這一點,而無需創建另一個接口('FixedMethods')? –

+0

我們也可以定義一個通用的類接口類型,並將其與一個方法名列表一起使用,參見本答案的第二部分。 – Jokester

1

這裏是另一種方式如果您不想創建另一個界面

interface MyFunctionType {(resource: string | Resource): Something} 

class MyClass { 
    // ... 

    someMethod() { /*...*/} 

    public someMethodThatConforms: MyFunctionType = (resource: string | Resource) => { 
     // ... 
     return new Something(/*...*/); 
    } 

    public anotherMethodThatConforms: MyFunctionType = (resource: string | Resource) => { 
     // ... 
     return new Something(/*...*/); 
    } 

    someOtherMethod() { /*...*/} 

    // ... 
} 
相關問題