我隐式编写的许多方法都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)
我知道这一点someMethodThatConforms并anotherMethodThatConforms符合接口,但现在我想知道如何断言这一点someMethodThatConforms并且anotherMethodThatConforms必须符合接口MyFunctionType(这样如果我更改,MyFunctionType就会引发错误)?
如果您不想创建另一个界面,这是另一种方法
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() { /*...*/}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我们可以定义另一个接口并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;
}
}
Run Code Online (Sandbox Code Playgroud)
更复杂的方式:使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1731 次 |
| 最近记录: |