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
?
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.
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”.
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.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With