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() { /*...*/ }
// ...
}
我知道someMethodThatConforms
和anotherMethodThatConforms
符合界面,但现在我想知道如何断言 someMethodThatConforms
和anotherMethodThatConforms
必须符合接口MyFunctionType
(如果我更改,则会抛出MyFunctionType
个错误)?
答案 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