TypeScript Union Types
up:: Typescript
Type1 | Type 2
means “either a Type1 or a Type2”
function isNumber(arg: string | number): boolean {
return typeof arg === 'number';
}
Gotchas
function getClevelandZipCode(): string | number {
return 44106;
}
let zip: string | number = getClevelandZipCode();
zip;
✅ returns 44106
function getClevelandZipCode(): string | number {
return 44106;
}
let zip: number = getClevelandZipCode();
zip;
⚠️ 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.