gpt4 book ai didi

typescript - "!"(爆炸符号)在属性(property)声明中意味着什么?

转载 作者:行者123 更新时间:2023-12-05 02:58:26 25 4
gpt4 key购买 nike

代码:

class Cat extends Animal { tag! : 'cat' }

什么是“!” tag 声明之后的意思?它与 tag 有何不同?

最佳答案

让我们看一个示例 - 假设我们有以下代码:

interface Animal {
tag: string;
}

class Cat implements Animal { tag: 'cat' }
class AnimalClass {
tag: string | undefined;
}

class Dog extends AnimalClass { tag: 'dog' }

两个代码片段都会抛出以下内容:Property 'tag' has no initializer and is not definitely assigned in the constructor.(2564)

这是在 2.7.2 中添加的 TypeScript 功能,其中包括严格的类检查,其中所有属性都应在其构造函数中声明。

通过添加爆炸符号 !,您将覆盖此行为并告诉编译器您“知道”它正在正确初始化并且以后不会未定义。

您也可以通过在编译器选项中设置 "strictPropertyInitialization": false 来禁用它。或者在应该初始化的地方初始化属性(根据 TypeScript):

class Dog extends AnimalClass { 
tag: string;

constructor() {
super();
this.tag = "";
}
}

关于typescript - "!"(爆炸符号)在属性(property)声明中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59053670/

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