2017-06-01 13 views
1

私が書いている多くの方法は暗黙のうちに同じfunction typeを書いています。私がしたいことは、特定のメソッドが関数型に従わなければならないことを明示的に指定できるように、この関数型を強制することです。typescriptのクラスメソッドに関数型インターフェイスを適用するにはどうすればよいですか?

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

一般的なインターフェースのような型を定義し、メソッド名のリストとともに使用することもできます。この答えの2番目の部分を参照してください。 – 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() { /*...*/} 

    // ... 
} 
関連する問題