In TS, question mark after defined method name

Viewed 370

I understand use of TS ? for declare optional params, fields, optional methods, etc. But I seen code that put ? after method that is defined in class, like this:

class Foo {
  public myMethod?(...) {
    ... code
  }
}

Why this is useful?

1 Answers

Just ran into this today. The ? after a method allows an implementing class to not implement that method. That is to say, implementing that method is optional. Can be done for interfaces or classes. If you choose to implement the optional method, you do not need to add the ? unless it is intended for a subsequent implementation to also be optional.

Here's a contrived example

export interface Foo {
    bar(): string;
    baz?(): string;
}

// Buzz can implement gazz optionally
export class Buzz implements Foo {
    readonly gar: string;

    readonly jazz: string;

    constructor() {
        this.gar = 'GAR!';
        this.jazz = 'jazz!';
    }

    bar() {
        return this.gar;
    }

    gazz() { // no ? means subsequent implementations need gazz
        return this.jazz;
    }
}

// Stuzz needs to implement method gazz, but does not
export class Stuzz implements Buzz {
    readonly gar: string;

    readonly jazz: string;

    constructor() {
        this.gar = 'ZAR!';
        this.jazz = 'jazz!';
    }

    bar() {
        return this.gar;
    }

  /**
   * Without gazz we get an error:
   * Class 'Stuzz' incorrectly implements class 'Buzz'. Did you mean to extend 'Buzz' and inherit its members as a subclass?
   * Property 'gazz' is missing in type 'Stuzz' but required in type 'Buzz'.
   */
    // gazz() {
    //     return this.jazz;
    // }
}

Related