首页 > 解决方案 > 如何使用静态和动态键为对象定义 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)

任何帮助或见解都会很棒

标签: typescriptreact-nativereact-redux

解决方案


推荐阅读