TypeScriptLesson 6 of 16
Type aliases and union types
The type keyword names any type, and | combines several types into a union. A value of that type can be any one of its members.
Key points
- type ID = number | string means the value is a number or a string.
- Before a check, only the operations shared by every member are allowed.
- After typeof id === "string", TypeScript knows it is a string inside the if.
- Both type and interface describe objects; only type can name a union.
Example
type ID = number | string;type Point = { x: number; y: number }; function showId(id: ID): string { if (typeof id === "string") { return `ID ${id.toUpperCase()}`; // here id is a string } return `ID #${id}`; // and here it is a number} const start: Point = { x: 0, y: 0 }; console.log(showId(42));console.log(showId("ab-7"));console.log(`Start: ${start.x},${start.y}`);Inside the if, id has toUpperCase because it is definitely a string there. After that return, only number is left. Point is a plain object type with a name.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Let Price be a number or a string, convert strings with parseFloat, add "12.50" to the array and print "499, 1250, 300" and "Sum: 2049".
Output
What your program prints appears here.