about summary refs log tree commit diff stats
path: root/ts/thinking-about-unions/left-pad.ts
blob: e75e38d7be558f512e9a9bb94452ac3dc2390615 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* 

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));