显然(我是初学者),ts在界面中不支持静态方法,但是有一个解决方法Val's对其进行了解释。当您的类只有静态方法时,它才起作用。但是如果我的课程是静态和非固定方法的组合,则会抛出错误:
Class 'MyClass' incorrectly implements interface 'sampleInterface'.
Property 'staticFunction' is missing in type 'MyClass' but required in type 'sampleInterface'
知道如何支持这一点吗?
export function staticDecorator<T>() {
return (constructor: T) => {};
}
interface sampleInterface {
staticFynction(/*something*/): promise<void>;
nonStaticFynction(/*something*/): promise<void>;
}
@staticDecorator()
class MyClass implements sampleInterface {
public static staticFynction(/*something*/): promise<void>{
//something
}
public nonStaticFynction(/*something*/): promise<void>{
//something
}
}
答案 0 :(得分:4)
通常,您需要两个接口;一个用于类的实例端,一个用于类的静态端。例如:
interface SampleInterfaceInstancePart {
nonStaticFunction(/*something*/): Promise<void>;
}
interface SampleInterfaceStaticPart {
staticFunction(/*something*/): Promise<void>;
}
然后,您可以使用staticDecorator
来确保该类实现静态端,并使用常规的旧implements
子句来确保它实现实例端:
@staticDecorator<SampleInterfaceStaticPart>()
class MyClass implements SampleInterfaceInstancePart {
public static async staticFunction(/*something*/): Promise<void> { }
public async nonStaticFunction(/*something*/): Promise<void> { }
}
希望有所帮助;祝你好运!