I need to display a carousel of items of two possible types (FirstType, SecondType). My carousel component requires an array as input, so I declared the items as the array of the union
type FirstType = {
a: 'first',
b: number
}
type SecondType = {
b: string
}
type Items = (FirstType | SecondType)[]
Now in my render function I get an Item of type FirstType | SecondType. I could identify the type by checking the presence of the a key, that is a constant on FirstType:
const renderItem = (item: FirstType | SecondType) => {
if (item.a === 'first') {
// Here I know that item is FirstType
} else {
// Here I know that item is SecondType
}
}
But this code gives me error:
Property 'a' does not exist on type FirstType | SecondType
How should I perform this check according to typescript?
Playground link
Probably the safest way to do this is with a custom type-guard
function isFirstType(item: FirstType | SecondType): item is FirstType {
return (item as FirstType).a === "first"; //or however you want to differentiate
}
then
const renderItem = (item: FirstType | SecondType) => {
if (isFirstType(item)) {
// item is narrowed to FirstType
} else {
// item is narrowed to SecondType
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With