diff options
author | elioat <elioat@tilde.institute> | 2024-07-04 16:47:31 -0400 |
---|---|---|
committer | elioat <elioat@tilde.institute> | 2024-07-04 16:47:31 -0400 |
commit | 3cacaed852a0e27bebdc33ad31351620596d3773 (patch) | |
tree | 67dbbfc8dc0fe24999abffb2a75a42f3bbf1ba33 | |
parent | 5d2993d7ad5b7a118421c2f783cfbeb1ab4aca00 (diff) | |
download | tour-3cacaed852a0e27bebdc33ad31351620596d3773.tar.gz |
*
-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 |