Typescript 键入默认值
是否有方法创建将用默认值声明的类型。 而不是写同样的声明:Typescript 键入默认值,typescript,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; } 更漂亮的是您可以使用默认值定义一个常量,并让推理处理该类型 cons
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;
}
更漂亮的是您可以使用默认值定义一个常量,并让推理处理该类型
const noString = '' // you can specify the type of the const
class Test {
a = noString;
b = noString;
c = noString;
}
在类型脚本中,类型和值共享不同的宇宙。类型注释无法同时为字段指定默认值
有没有办法创建将用默认值声明的类型
不,这是不可能的,因为:您声明了一个变量,而不是定义它,因此您实际上没有设置任何值,您必须在某处进行设置
有些语言对某些情况()进行默认初始化,但TypeScript只能默认初始化为undefined
因此,您可以选择以下选项:
a:string=''代码>
constructor(){this.a='';}