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
missymae
missymae13mo ago
const Iconos: {house:string, appartment:string}= {
house: 'IconOfHome',
appartment: 'IconOfAppartment',
}

type HomeTypes = "house" | "appartment";


const homes:HomeTypes[] = ["house", "appartment"]


const iconos = homes.map(home => Iconos[home])

console.log(iconos) // ['IconOfHome','IconOfAppartment']
const Iconos: {house:string, appartment:string}= {
house: 'IconOfHome',
appartment: 'IconOfAppartment',
}

type HomeTypes = "house" | "appartment";


const homes:HomeTypes[] = ["house", "appartment"]


const iconos = homes.map(home => Iconos[home])

console.log(iconos) // ['IconOfHome','IconOfAppartment']
Like this?
Nash
Nash13mo ago
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]
Want results from more Discord servers?
Add your server