Welcome to the TypeScript community!
Let's delve into what is happening here:Array<string>
(also written as string[]
) represents a structure like ['a', 'b', 'c']
. It differs from the structure you provided:
[{city:'New York', ['zoneA','ZoneB']}]
, hence the failure.
To resolve this issue, I suggest changing the type from Array<string>
to City[]
(or Array<City>
). The City
type should be defined as below:
type City = {
city: string;
zones: string[];
};
You can then utilize it in this manner:
export const cityToZone: City[] = [{
city: 'New York',
zones: ['zoneA','ZoneB']
}];
For further enhancement, incorporate union types for city names and zones as shown below:
type CityName = 'New York' | 'Denver' | 'Washington, D.C.'; // etc
type ZoneName = 'Zone 1' | 'Zone 2' | 'Zone 3'; // etc
This will modify your City
type to look like this:
type City = {
city: CityName;
zones: ZoneName[];
}
Update: Feel free to experiment with this on CodeSandbox: https://codesandbox.io/s/typescript-j90gi?fontsize=14&hidenavigation=1&theme=dark
Update 2 (mapping question): If your city names are unique, consider restructuring your data into
type CityMap = Record<CityName, ZoneName[]>;
and implement it like so:
export const cityToZone: CityMap = {
'New York': ['zoneA', 'zoneB'],
'Denver': ['zoneC', 'zoneD'],
};
This approach allows you to retrieve zones by city name in constant time (O(1))