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



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

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);

打字稿显示了错误:

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游乐场

最新更新