我的代码:
const WEEKDAYS_SHORT: string[] = ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam']
Run Code Online (Sandbox Code Playgroud)
错误消息来自TypeScript(3.0)编译器:
TS2322:类型'string []'不能赋值为'[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
}
Run Code Online (Sandbox Code Playgroud)
如何在TypeScript中定义只读数组?
Mat*_*vic 32
You may add as const to your declaration;
const readonlyArray = [1, 2, 3] as const;
Run Code Online (Sandbox Code Playgroud)
Furthermore the type typeof readonlyArray[number] would be 1 | 2 | 3
Tit*_*mir -1
正如您所指出的,问题的原因是您尝试将字符串数组 ( string[]) 分配给 7 字符串元组。虽然您要使用的解决方案any可行,但通常不建议使用any. 拼写出柔顺也不太理想,因为它太长了。
我们可以做的是创建一个辅助函数来创建元组类型。该函数可在任何需要元组的地方重用:
function tupleArray<T extends any[]>(...v: T) {
return v;
}
const WEEKDAYS_SHORT_INFFERED = tupleArray('Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam') // INFFERED AS [string, string, string, string, string, string, string]
const WEEKDAYS_SHORT: [string, string, string, string, string, string, string] = WEEKDAYS_SHORT_INFFERED
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5637 次 |
| 最近记录: |