diff options
Diffstat (limited to 'ts/thinking-about-unions/left-pad.ts')
-rw-r--r-- | ts/thinking-about-unions/left-pad.ts | 27 |
1 files changed, 14 insertions, 13 deletions
diff --git a/ts/thinking-about-unions/left-pad.ts b/ts/thinking-about-unions/left-pad.ts index e75e38d..95f6d51 100644 --- a/ts/thinking-about-unions/left-pad.ts +++ b/ts/thinking-about-unions/left-pad.ts @@ -1,9 +1,9 @@ -/* +/* 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. +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. */ @@ -11,16 +11,17 @@ 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}'.`); -} + switch (typeof padding) { + case "number": + return Array(padding + 1).join(" ") + value; // 0 indexing is for computers, this function is for people. + case "string": + return padding + value; + default: + throw new Error(`Expected number or string, got '${padding}'.`); + } +}; -const marioMsg = 'It is I, Mario!'; +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 +console.log(leftPad(marioMsg, "*** ")); +// console.log(leftPad(marioMsg, true)); |