Lessons · TypeScript · union types
One of several types
string | number means 'either'. Until you check which, you may only use what both have.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Ids that arrive as strings or numbers, values that may be null, results that are a value or an error: unions model real data honestly.
How to think about it
Which types can actually arrive here? Write the union that matches reality. Then, before using a member-specific method, narrow with a check the compiler understands.
Worked example
function len(x: string | string[]): number {Either a string or an array of them.return x.length;Both have length, so this is allowed without a check.
}
function up(x: string | number) { return x.toUpperCase(); }Error: number has no toUpperCase. Needs narrowing.Your turn
Type a value that may be text or missing.
let nick: string null = null;
Solve one with the compiler running
The trap
Casting your way out with 'as string'. That tells the compiler to stop checking, which is the opposite of the point.
Practise union types on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.