Union Types
A union allows several types with |. Use narrowing to work with each one.
Example
function id(x: string | number) {
return typeof x === "number" ? x + 1 : x + "!";
}
console.log(id(1), id("a"));Result
2 a!
Exercise
Either type.
let x: | number;
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.