typescript - 如何使用静态和动态键为对象定义 TypeScript 类型?
问题描述
我有一个标准化的 redux 结构addressesState
,如下所示。我需要定义注释中指定的类型
interface iAddressItem {
firstName: string;
lastName: string;
street: string;
}
const addressesState = {
// key "ids" is static
// value is Array<string>
ids: ["1345", "1346"],
// typeof key is string and it is dynamic
// typeof value is iAddressItem
"1345": {
firstName: "Cinta",
lastName: "Riardo",
street: "Cake Street 34",
},
// typeof key is string and it is dynamic
// typeof value is iAddressItem
"1346": {
firstName: "Nosipho",
lastName: "Tracey",
street: "Baker Street 42",
},
};
我尝试将addressesState的类型定义如下:
type AddressesType = {
[key in string | number]?: iAddressItem;
} & {
ids?: Array<number>;
};
但是当我将 redux 状态初始化为:
const initalAddressesState: AddressesType = {
ids: []
}
我收到错误:
Type '{ ids: never[]; }' is not assignable to type 'AddressesType'.
Type '{ ids: never[]; }' is not assignable to type '{ [x: string]: iAddressItem | undefined; [x: number]: iAddressItem | undefined; }'.
Property 'ids' is incompatible with index signature.
Type 'never[]' is missing the following properties from type 'iAddressItem': firstName, lastName, street(2322)
任何帮助或见解都会很棒
解决方案
推荐阅读
- svg - 如何旋转svg的一部分?
- json - 如何提交应该在同一个 Vuex Store 对象中并且未映射到 store 对象的多个嵌套值?
- oracle - Sybase 到 Oracle 表的移动
- sql - 考虑到许多因素,我如何计算任务完成日期
- r - R for 循环返回 NULL 而不是预期值
- angular - 角度计算 ngfor 累积值和通过父级的总计
- javascript - 使用 service-worker.js 中的方法在 EDGE 和 IE11 对象中出现错误不支持属性或方法“waitUntil””
- electron - Chromium 在哪里加载扩展?
- javascript - 如何登录应用程序页面并将页面定向到主页?
- user-interface - Tkinter表面在exe中显示错误