Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript abstract optional method

Tags:

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; 
like image 448
Murat Karagöz Avatar asked May 24 '17 08:05

Murat Karagöz


People also ask

Is abstract optional?

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.

How can we call abstract class method in TypeScript?

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.

Is optional class is an abstract class?

Abstract methods defined in classes cannot be marked as optional.

Does TypeScript support abstract class?

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.


2 Answers

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

like image 71
idsbllp Avatar answered Oct 07 '22 18:10

idsbllp


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.

like image 44
Coderer Avatar answered Oct 07 '22 18:10

Coderer