diff options
-rw-r--r-- | ts/thinking-about-unions/left-pad.ts | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/ts/thinking-about-unions/left-pad.ts b/ts/thinking-about-unions/left-pad.ts new file mode 100644 index 0000000..e75e38d --- /dev/null +++ b/ts/thinking-about-unions/left-pad.ts @@ -0,0 +1,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)); \ No newline at end of file |