相关疑难解决方法(0)

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

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

例如

interface MyFunctionType {(resource: string | Resource): Something}
Run Code Online (Sandbox Code Playgroud)

我的类有一些符合这个接口的方法。

class MyClass {
    // ...

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

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

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

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我知道这一点someMethodThatConformsanotherMethodThatConforms符合接口,但现在我想知道如何断言这一点someMethodThatConforms并且anotherMethodThatConforms必须符合接口MyFunctionType(这样如果我更改,MyFunctionType就会引发错误)?

typescript

6
推荐指数
2
解决办法
1731
查看次数

标签 统计

typescript ×1