输入默认值

时间:2018-11-11 18:53:26

标签: typescript

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

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

更漂亮

2 个答案:

答案 0 :(得分:1)

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

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

}

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

答案 1 :(得分:0)

  

有什么方法可以创建将声明为默认值的类型

不,这是不可能的,因为:您声明了o变量,没有定义它,因此您实际上并没有设置任何必须在某处执行的值。

有些语言在某些情况下会进行默认初始化(C++ is an example),但是TypeScript只能默认初始化为undefined when --strictPropertyInitialization flag is not used

因此,您将获得以下选项:

  1. 您现在正在做什么:a: string = '';
  2. 构造函数中的初始化:constructor() { this.a = ''; }
相关问题