TypeScript Union Types
up:: Typescript
Type1 | Type 2
means “either a Type1 or a Type2”
Gotchas
✅ returns 44106
⚠️ Type Error!
It might seems a bit strange that the last code block throws a type error. But TypeScript doesn’t try to infer a ‘better’ type than the one we provided. The compiler only checks again string | number
. Type number
is equal to string | number
, so it throws a type error.