I have an abstract class with some abstract methods. Is there a way to mark some of these methods as optional?
abstract class Test { protected abstract optionalMethod?(): JSX.Element[]; protected abstract requiredMethod(): string; }
For some reasons I can add the ?
as a suffix but it seems like it does nothing at all because I have to still implement the method in the derived class. For now I am using it like this to mark it that it can return null
which is basically the poor mans optional.
protected abstract optionalMethod?(): JSX.Element[] | null;
In an abstract interface keyword, is optional for declaring a method as an abstract. In an abstract class, the abstract keyword is compulsory for declaring a method as an abstract. An interface can have only public abstract methods. An abstract class has protected and public abstract methods.
abstract class Person { name: string; constructor(name: string) { this.name = name; } display(): void{ console. log(this.name); } abstract find(string): Person; } class Employee extends Person { empCode: number; constructor(name: string, code: number) { super(name); // must call super() this.
Abstract methods defined in classes cannot be marked as optional.
TypeScript has supported abstract classes since 2015, which provides compiler errors if you try to instantiate that class. TypeScript 4.2 adds support for declaring that the constructor function is abstract.
You can do this with class
and interface
merging:
interface Foo { print?(l: string): void; } abstract class Foo { abstract baz(): void; foo() { this.print && this.print('foo'); } } class Bar extends Foo { baz(): void { if (this.print) { this.print('bar'); } } }
Link to the above code in the Typescript playground
I'm not sure if this changed at some point, but today (TS 4.3) you can simply make the base-class optional method non abstract:
abstract class Base { protected abstract required(): void; protected optional?(): string; print(): void { console.log(this.optional?.() ?? "Base"); } } class Child1 extends Base { protected required(): void { } } class Child2 extends Base { protected required(): void { } protected optional(): string { return "Child"; } } const c1 = new Child1(); c1.print(); const c2 = new Child2(); c2.print();
Try it on the TS Playground.
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