【问题标题】:How can I define an interface or type in TypeScript for my constant?如何在 TypeScript 中为常量定义接口或类型?
【发布时间】:2021-07-06 22:38:15
【问题描述】:

我正在尝试为我的数据集定义接口或类型,但出现了一些错误。下面是我使用的错误接口和代码:

interface IVehicle {
    [key: number]: { model: string, year: number };
}
interface IVehicles {
    [type: string]: Array<IVehicle>
}

const DATASET: IVehicles = {
    CAR: [
        ["BMW", {
            model: "520d",
            year: 2015,
        }],
        ["Audi", {
            model: "A4",
            year: 2011,
        }]
    ],
    MOTORCYCLE: [
        ["YAMAHA", {
            model: "R6",
            year: 2020,
        }],
        ["DUCATI", {
            model: "Monster",
            year: 2018,
        }]
    ]
}

console.log(DATASET);

Typescript 向我显示了错误:

Type 'string' is not assignable to type '{ model: string; year: number; }'.

TypeScript Playground 代码: Playground Link

【问题讨论】:

  • 我认为你想要一个 元组类型{ [key: number]: { ... } } 对于你只期望两个值的数组没有意义,其中一个你期望 不是 成为那个形状的对象。

标签: javascript typescript types interface


【解决方案1】:

你可以使用

type IVehicle = [string, { model: string, year: number }];

interface IVehicles {
    [type: string]: Array<IVehicle>
}

TypeScript playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多