This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Introduction | |
| type Human = { | |
| name: string, | |
| age: number | |
| } | |
| type Alien = { | |
| name: string, | |
| planet: string | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Practical example | |
| //https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types | |
| function padLeft(value: string, padding: string | number) { | |
| if (typeof padding === "number") { | |
| return Array(padding + 1).join(" ") + value; | |
| } | |
| if (typeof padding === "string") { | |
| return padding + value; | |
| } | |
| throw new Error(`Expected string or number, got '${padding}'.`); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Discriminated Unions | |
| type Human2 = { | |
| kind: 'human', | |
| name: string, | |
| age: number, | |
| } | |
| type Alien2 = { | |
| kind: 'alien', | |
| name: string, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type InternalError = { | |
| kind: 'internalerror', | |
| error: string, | |
| details?: string[] | |
| } | |
| type BadDataError = { | |
| kind: 'baddata', | |
| error: string, | |
| data: any |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type Human2 = { | |
| kind: 'human', | |
| name: string, | |
| age: number, | |
| } | |
| type Alien2 = { | |
| kind: 'alien', | |
| name: string, | |
| planet: string |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| "use strict"; | |
| function sayHello2(named) { | |
| switch (named.kind) { | |
| case "human": | |
| console.log(`Hi ${named.name}`); | |
| break; | |
| case 'alien': | |
| console.log(`Hi ${named.name} from ${named.planet}`); | |
| break; | |
| } |