如何在打字稿中对类方法强制执行函数类型接口?

时间:2017-06-01 10:50:39

标签: typescript

class我写作的许多方法都有相同的function type。我想要做的是强制执行此函数类型,以便我可以明确声明某些方法必须符合函数类型。

e.g。

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个错误)?

2 个答案:

答案 0 :(得分:2)

这是另一种方式如果你不想创建另一个界面

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() { /*...*/}

    // ...
}

答案 1 :(得分:1)

我们可以定义另一个界面并让sudo journalctl -u bootkube实现它:

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