Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 13 additions & 27 deletions apps/typescript/47-enums-vs-union-types/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import { Component, computed, signal } from '@angular/core';

enum Difficulty {
EASY = 'easy',
NORMAL = 'normal',
}
const Difficulty = {
EASY: 'easy',
NORMAL: 'normal',
} as const;
type Difficulty = (typeof Difficulty)[keyof typeof Difficulty];

enum Direction {
LEFT = 'left',
RIGHT = 'right',
}
type Direction = { [K in 'left' | 'right']: string };

@Component({
imports: [],
selector: 'app-root',
template: `
<section>
<div>
<button mat-stroked-button (click)="difficulty.set(Difficulty.EASY)">
<button mat-stroked-button (click)="difficulty.set('easy')">
Easy
</button>
<button mat-stroked-button (click)="difficulty.set(Difficulty.NORMAL)">
<button mat-stroked-button (click)="difficulty.set('normal')">
Normal
</button>
</div>
Expand All @@ -28,10 +26,8 @@ enum Direction {

<section>
<div>
<button mat-stroked-button (click)="direction.set(Direction.LEFT)">
Left
</button>
<button mat-stroked-button (click)="direction.set(Direction.RIGHT)">
<button mat-stroked-button (click)="direction.set('left')">Left</button>
<button mat-stroked-button (click)="direction.set('right')">
Right
</button>
</div>
Expand All @@ -55,11 +51,8 @@ enum Direction {
`,
})
export class AppComponent {
readonly Difficulty = Difficulty;
readonly difficulty = signal<Difficulty>(Difficulty.EASY);

readonly Direction = Direction;
readonly direction = signal<Direction | undefined>(undefined);
readonly direction = signal<keyof Direction | undefined>(undefined);

readonly difficultyLabel = computed<string>(() => {
switch (this.difficulty()) {
Expand All @@ -71,14 +64,7 @@ export class AppComponent {
});

readonly directionLabel = computed<string>(() => {
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!';
}
if (!this.direction()) return 'Choose a direction!';
return `You chose to go ${this.direction()}`;
});
}
Loading