首页 > 解决方案 > 输入默认值

问题描述

有什么方法可以创建将使用默认值声明的类型。而是编写相同的声明:

class Test{
a: string = '';
b: string = '';
c: string = '';
...
}

[顺便提一句。看起来很糟糕]只写类型

class Test{
a: type_with_default_value;
b: type_with_default_value;
c: type_with_default_value;
}

漂亮多了

标签: typescript

解决方案


您可以使用默认值定义一个常量,并让推理处理类型

const noString = '' // you can specify the type of the const 
class Test {
  a = noString;
  b = noString;
  c = noString;

}

在 Typescript 中,类型和值共享不同的宇宙。类型注释无法同时为字段分配默认值。


推荐阅读