class
我正在编写的许多方法都隐式具有相同的函数类型。我要执行的是强制执行此函数类型,以便我可以明确声明某些方法必须符合该函数类型。
例如
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
错误抛出)?
我们可以定义另一个接口并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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句