typescript - 打字稿类型 Never[] 不可分配给对象数组
问题描述
我正在尝试创建一个对象数组,例如:
objectExample[a].push({ id: john, detail: true });
objectExample[a].push({ id: james, detail: false});
const objectExample = {
a = [ { id: john, detail: true},
{ id: james, detail: false}];
}
如果我在打字稿中尝试这个:
const objectExmaple: { [key: string]: { [key: string]: string | boolean}[]} = [];
我在 objectType 上收到此错误:
Type 'never[]' is not assignable to type '{ [key: string]: { [key: string]: string | boolean; }[]; }'.
Index signature is missing in type 'never[]'.ts(2322)
如何解决此错误?
解决方案
有几个问题:
- 如果它是一个对象
objectExample
,则无法初始化[]
- 类型定义很复杂
type Item = { [key: string]: string | boolean}
// Same as type Item = { [key: string]: string | boolean}
const objectExample: Record<string, Item[]> = {
a: [ { id: 'john', detail: true},
{ id: 'james', detail: false}]
}
objectExample.a.push({ id: 'john', detail: true });
objectExample.a.push({ id: 'james', detail: false});
这是一个工作游乐场的链接
推荐阅读
- spring-boot - 是否可以将 PointCut 添加到 ModelAndView 方法?
- eclipse-plugin - 如何在 Eclipse Photon 4.8.x 版本上安装 Atlassian 连接器
- javascript - 如何根据反应谷歌图表中散点图中的某个范围值显示点颜色
- arrays - 如何删除包含列表的字典列表中的重复项?
- dart - 使用通用 bloc 提供程序时 bloc 未初始化
- python-3.x - pyodbc 无法连接到本地 MSSQL 服务器
- css - 基础 6 遵守不显示消息
- c# - 为什么我的 HTTP POST 正文内容被接收/处理为 NULL?
- c# - 比较日期的问题
- datatables - DataTables - 大屏幕上的响应式隐藏列