Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an interface with static method?

Tags:

typescript

I want to declare an alternative constructor in interface - baz in IFoo, but seems like it's impossible in TypeScript:

interface IFoo {
    bar(): boolean;
    static baz(value): IFoo; 
}

class Foo implements IFoo {
    constructor(private qux) {}
    bar(): boolean {
        return this.qux; 
    }
    static baz(value): IFoo {
        return new Foo(value);
    }
}

What is the way to do that and have a proper type checking for baz?

like image 428
Gill Bates Avatar asked Nov 15 '15 12:11

Gill Bates


People also ask

Can you declare an interface method static?

Static methods in an interface since java8 Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.

Why static method is not allowed in interface?

Java interface static method helps us in providing security by not allowing implementation classes to override them. We can't define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”.

What is the use of static method in interface?

Static methods provide default methods that implementing classes do not to override. Its particularly useful if the the method logic is replicated across all the implementations. Your example is useful, say classes PopSong and RockSong can implement it and both would have default scale as A minor.

Can we declare static method in interface C#?

Note that you can have static methods that work with interfaces, you just cannot define them within the interface because there is no way to correctly reference them.


1 Answers

you can do this with anonymous classes:

In general

export const MyClass: StaticInterface = class implements InstanceInterface {
}

Your example:

interface IFooStatic {
  baz(value): IFoo;
}

interface IFoo {
  bar(): boolean;
}

const Foo: IFooStatic = class implements IFoo {
  constructor(private qux) {}
  bar(): boolean {
    return this.qux; 
  }
  static baz(value): IFoo {
    return new Foo(value);
  }
}
like image 151
chris Avatar answered Sep 18 '22 15:09

chris