Typescript type for array passed as string
I'm trying to convert a comma-separated string(knowing the possible variations) to an array using each element of the array as key of a dictionary of icons.
Does anybody knows how to do this?
const Iconos = {
house: 'IconOfHome',
appartment: 'IconOfAppartment',
}
type HomeTypes = "house" | "appartment";
type HomeArrayType =
|
${HomeTypes}
| ${HomeTypes}, ${HomeTypes}
const homes:HomeArrayType = 'appartment, house'
const homesArray:Array<HomeArrayType> = homes.split(homes)
// here homesArray shows the following error: Type 'string[]' is not assignable to type 'HomeArrayType[]'.
Type 'string' is not assignable to type 'HomeArrayType'.(232
const iconos = homesArray.map(home => Iconos[home])
// here Iconos[home] showsthe following error: Element implicitly has an 'any' type because expression of type 'HomeArrayType' can't be used to index type '{ house: string; appartment: string; }'.
Property 'house, house' does not exist on type '{ house: string; appartment: string; }'.(7053)2 Replies
Like this?
Yup but the thing is that
homes
is hardcoded, is coming from a JSON response, I've modified the code to only allow 2 Icons but in reality there is actually 4 variations of Icons. e.g. could be house, apartment
or apartment, apartment
or apartment house
I realized I can force(cast) the string to be a string literal Iconos[<HomeTypes>home]