4

so apparently (i'm beginner) ts doesn't support static methods in the interface however there is a workaround explained it Val's answer. it works when your class has only static methods. but if my class is a combination of static and non-satic methods this will throw an error:

Class 'MyClass' incorrectly implements interface 'sampleInterface'.
  Property 'staticFunction' is missing in type 'MyClass' but required in type 'sampleInterface'

any idea how to support this?

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
    }
}

1 Answer 1

7

Generally you need two interfaces; one for the instance side of the class, and one for the static side of the class. For example:

interface SampleInterfaceInstancePart {
  nonStaticFunction(/*something*/): Promise<void>;
}
interface SampleInterfaceStaticPart {
  staticFunction(/*something*/): Promise<void>;
}

Then you can use your staticDecorator to ensure that the class implements the static side, and the regular old implements clause to ensure that it implements the instance side:

@staticDecorator<SampleInterfaceStaticPart>()
class MyClass implements SampleInterfaceInstancePart {
  public static async staticFunction(/*something*/): Promise<void> { }
  public async nonStaticFunction(/*something*/): Promise<void> { }
}

Hope that helps; good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to ensure that the static interface is also implemented correctly by the class? So similiar to implements SampleInterfaceInstancePart but for the static part?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.