我有一个类型为[number, number]
的字段,并且对TypeScript编译器(strict
设置为true
)的问题抱怨初始值。我尝试了以下内容:
public sheet: [number, number];
- 抛出error TS2564: Property 'sheet' has no initializer and is not definitely assigned in the constructor.
public sheet: [number, number] = [];
- 抛出error TS2322: Type 'never[]' is not assignable to type '[number, number]'.
public sheet: [number, number] = [] as [number, number];
与上述相同我知道我可以创建一个像public sheet: [number, number] = [] as any as [number, number];
这样的小怪物(或指定[0, 0]
我不想做的事情但是我想知道是否有更好的方法。你有什么想法吗?
答案 0 :(得分:3)
此错误来自strictOption启用的compilerOption strictPropertyInitialization
。
您可以使用 definite assignment assertion modifier !
告诉typscript在其他位置初始化:
public sheet!: [number, number];