Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Determine object subtype from union type by checking the presence of some properties

Tags:

typescript

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

like image 745
gbalduzzi Avatar asked Oct 14 '25 15:10

gbalduzzi


1 Answers

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
  }
}
like image 91
spender Avatar answered Oct 19 '25 01:10

spender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!