Unions and Literal Types
A union type uses | to allow several types. Literal types limit a value to exact options. Narrow a union with typeof, in or equality checks and TypeScript follows along.
Example
type Id = string | number;
function show(id: Id) {
if (typeof id === "string") return id.toUpperCase();
return id.toFixed(1);
}
console.log(show("ab"), show(7));
type Dir = "up" | "down";
const d: Dir = "up";
console.log(d);Result
AB 7.0 up
Exercise
Finish the union.
type Id = string | ;
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.