diff --git a/apps/typescript/47-enums-vs-union-types/src/app/app.component.ts b/apps/typescript/47-enums-vs-union-types/src/app/app.component.ts index 05886724f..887a604ca 100644 --- a/apps/typescript/47-enums-vs-union-types/src/app/app.component.ts +++ b/apps/typescript/47-enums-vs-union-types/src/app/app.component.ts @@ -1,25 +1,27 @@ import { Component, computed, signal } from '@angular/core'; -enum Difficulty { - EASY = 'easy', - NORMAL = 'normal', -} +type Difficulty = keyof typeof difficulties; +const difficulties = { + easy: 'Easy', + normal: 'Normal', +} as const; -enum Direction { - LEFT = 'left', - RIGHT = 'right', -} +type Direction = 'left' | 'right'; +type DirectionMap = { [K in Direction]: string }; +const directions: DirectionMap = { + left: 'left (←)', + right: 'right (→)', +} as const; @Component({ - imports: [], selector: 'app-root', template: `
- -
@@ -28,10 +30,8 @@ enum Direction {
- - +
@@ -53,30 +53,16 @@ enum Direction { `, }) export class AppComponent { - readonly Difficulty = Difficulty; - readonly difficulty = signal(Difficulty.EASY); + readonly difficulty = signal('easy'); - readonly Direction = Direction; readonly direction = signal(undefined); - readonly difficultyLabel = computed(() => { - switch (this.difficulty()) { - case Difficulty.EASY: - return Difficulty.EASY; - case Difficulty.NORMAL: - return Difficulty.NORMAL; - } - }); + readonly difficultyLabel = computed( + () => difficulties[this.difficulty()], + ); readonly directionLabel = computed(() => { - const prefix = 'You chose to go'; - switch (this.direction()) { - case Direction.LEFT: - return `${prefix} ${Direction.LEFT}`; - case Direction.RIGHT: - return `${prefix} ${Direction.RIGHT}`; - default: - return 'Choose a direction!'; - } + const dir = this.direction(); + return dir ? `You chose to go ${directions[dir]}` : 'Choose a direction'; }); }