I am trying to create a carousel that displays items of two different types (FirstType
, SecondType
). The carousel component I am using requires an array as input, so I have declared the items as an array union like this:
type FirstType = {
a: 'first',
b: number
}
type SecondType = {
b: string
}
type Items = (FirstType | SecondType)[]
In my render function, I receive an Item of type FirstType | SecondType
. To determine the type, I planned on checking the presence of the key a
, which is unique to FirstType
:
const renderItem = (item: FirstType | SecondType) => {
if (item.a === 'first') {
// Item is of type FirstType
} else {
// Item is of type SecondType
}
}
However, I encountered an error when implementing this code:
Property 'a' does not exist on type FirstType | SecondType
How can I successfully perform this check in TypeScript?