我需要创建一个预定义的字典,键是城市,值是该城市中的区域数组。我尝试过类似的东西
export const cityToZone: { [city: string]: Array<string> } = [
{city:'New York', ['zoneA','ZoneB']}
]
但是我不断收到一个错误,说:
(TS) Type '{ city: string; ['zoneA','ZoneB']: any; }' is not assignable to type 'string[]'. Object literal may only specify known properties, and 'city' does not exist in type 'string[]'.
我是打字稿的新手,我不知道这里出了什么问题。
欢迎来到 TypeScript 社区 <3
让我详细说明这里发生的事情:Array<string>
(或string[]
,因为它们的意思相同(代表像['a', 'b', 'c']
这样的结构。它与你通过的那个不同:[{city:'New York', ['zoneA','ZoneB']}]
,因此它失败了。
有几种方法可以解决此问题。我建议您将类型从Array<string>
更改为City[]
(或Array<City>
(。根据使用情况,City
类型应描述如下:
type City = {
city: string;
zones: string[];
};
您可以按如下方式使用它:
export const cityToZone: City[] = [{
city: 'New York',
zones: ['zoneA','ZoneB']
}];
如果要更进一步,可以将联合类型用于城市名称和区域:
type CityName = 'New York' | 'Denver' | 'Washington, D.C.'; // etc
type ZoneName = 'Zone 1' | 'Zone 2' | 'Zone 3'; // etc
因此,您的City
类型将如下所示:
type City = {
city: CityName;
zones: ZoneName[];
}
UPD:你可以在CodeSandbox上玩它:https://codesandbox.io/s/typescript-j90gi?fontsize=14&hidenavigation=1&theme=dark
UPD 2(映射问题(:如果你的城市名称是唯一的(例如,你不必考虑"莫斯科,俄罗斯"和"莫斯科,爱达荷"这样的情况(,我建议你重新塑造你的数据结构
type CityMap = Record<CityName, ZoneName[]>;
并像这样使用它:
export const cityToZone: CityMap = {
'New York': ['zoneA', 'zoneB'],
'Denver': ['zoneC', 'zoneD'],
};
这样,您可以在恒定时间内按城市名称获取区域(O(1((