gpt4 book ai didi

typescript - 在 TS 中,定义方法名称后的问号

转载 作者:行者123 更新时间:2023-12-04 12:35:12 26 4
gpt4 key购买 nike

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

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

为什么这是有用的?

最佳答案

今天刚碰到这个。 ?在方法允许实现类不实现该方法之后。也就是说,实现该方法是可选的。
可以为接口(interface)或类完成。如果选择实现可选方法,则不需要添加?除非它的后续实现也是可选的。
这是一个人为的例子

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

关于typescript - 在 TS 中,定义方法名称后的问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62360856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com