Union types
A union type indicates that a value can be of one among several types,
using |.
let id: number | string;
id = 42; // valid
id = "abc"; // also valid
// id = true; // ❌ Error
function format(value: number | string): string {
return `Value: ${value}`;
}
To work with unions safely you use type checks:
function describe(x: number | string): string {
if (typeof x === "number") return `number ${x.toFixed(2)}`;
return `text of ${x.length} characters`;
}
Generics (introduction)
Generics let you write code that works with any type
without losing the type information. They are written with <T>.
function first<T>(arr: T[]): T {
return arr[0];
}
const n = first([1, 2, 3]); // T = number, n is number
const s = first(["a", "b"]); // T = string, s is string
This way, first preserves the type of the elements of the array it receives,
instead of returning any.
Examples
The generic logic works the same in JS
function first(arr) {
return arr[0];
}
function describe(x) {
if (typeof x === "number") return "number " + x.toFixed(2);
return "text of " + x.length + " characters";
}
console.log(first([10, 20, 30]));
console.log(describe(3.14159));
console.log(describe("hi"));