如何在 TypeScript 中为常量定义接口或类型?

How can I define an interface or type in TypeScript for my constant?

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

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

你可以使用

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

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

TypeScript playground