【发布时间】:2019-01-23 00:59:21
【问题描述】:
我的代码:
const WEEKDAYS_SHORT: string[] = ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam']
错误信息来自 TypeScript (3.0) 编译器:
TS2322:类型 'string[]' 不可分配给类型 '[string, string, string, string, string, string, string]'。 “字符串[]”类型中缺少属性“0”。
如果我把string[]改成ReadonlyArray<string>,那么错误信息就变成了:
TS2322:类型“ReadonlyArray”不可分配给类型“[string, string, string, string, string, string, string]”。 “ReadonlyArray”类型中缺少属性“0”。
我的 tsconfig.json:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"target": "es5",
"jsx": "react",
"strict": true
},
"exclude": [
"**/*.spec.ts",
"node_modules",
"vendor",
"public"
],
"compileOnSave": false
}
如何在 TypeScript 中定义只读数组?
【问题讨论】:
-
无法重现您的错误,即使使用
strict: true。 typescriptlang.org/play/… -
嘿 @TitianCernicova-Dragomir 我添加了 tsconfig.json
标签: arrays typescript