I have an array with a combination of strings and objects. Then I tried to display the properties of the array based on the key in a loop. Is it possible to do this in typescript?
This is the sample code:
const arr = [
{ name: 'John' },
'Amber',
{ name: 'Cathrine' },
'Louis',
{ name: 'Mike' }
]
arr.forEach((item, key) => {
if (typeof item !== 'string') {
console.log(item.name) // Works
console.log(arr[key].name) // Doesn't work, losing type
}
}
Please check this link to run the code: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDA2gKBjA3jMOAWwFMAuGAcgCkQALMSmAXwBpsqBBIgIxIUrsc+QqQqUAwnCh0EASzAkmbDpQAyIAK5yIgjiOLkqAWTkBrJS0wBdTJkQIAdADMQCAKJxgdABQ+5UCRErDAWAJ4AlKgAfHgccs4wPlBhAA4kIIkBQTAAhCholNDyYADmlFG4HDigkCAANiSO9SCl-oFEjqIkUQD0vTAA6m5mENUwtRANTS1tDujh1l2GfQMAIiAkEIywAO4jIS0gEAqlMCnpHMyYzEA
I really appreciate your help, Thank you!
const myItem = arr[key]; if(typeof myItem !== 'string') { console.log(myItem.name); }orconsole.log((arr[key] as {name: string}).name)