blob: e75e38d7be558f512e9a9bb94452ac3dc2390615 (
plain) (
tree)
|
|
/*
A stupidly simple example of unions.
Unions can be used to describe a type that is actually several different types.
Here, the Padding type is a union of either a number or a string.
Then, leftPad uses the union type so that it can accept either sort of type.
*/
type Padding = number | string;
const leftPad = (value: string, padding: Padding) => {
if (typeof padding === 'number') {
return Array(padding + 1).join(' ') + value; // 0 indexing is for computers, this function is for people.
}
if (typeof padding === 'string') {
return padding + value;
}
throw new Error(`Expected number or string, got '${padding}'.`);
}
const marioMsg = 'It is I, Mario!';
console.log(leftPad(marioMsg, 4));
console.log(leftPad(marioMsg, "****"));
console.log(leftPad(marioMsg, true));
|