TS中,定义的方法名后面加问号

zla*_*ski 6 typescript

我理解使用 TS?来声明可选参数、字段、可选方法等。但是我看到代码放在?类中定义的方法之后,如下所示:

class Foo {
  public myMethod?(...) {
    ... code
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么这个有用?

小智 8

今天刚遇到这个。方法?后面允许实现类实现该方法。也就是说,实现该方法是可选的。可以针对接口或类完成。如果您选择实现可选方法,则不需要添加 ,?除非后续实现也是可选的。

这是一个人为的例子

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;
    // }
}

Run Code Online (Sandbox Code Playgroud)