Skip to content

Answer:47 #1284

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
49 changes: 13 additions & 36 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,18 @@
import { Component, computed, signal } from '@angular/core';

enum Difficulty {
EASY = 'easy',
NORMAL = 'normal',
}

enum Direction {
LEFT = 'left',
RIGHT = 'right',
}
type Difficulty = { [K in 'EASY' | 'NORMAL']: string };
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 +21,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 @@ -53,30 +44,16 @@ enum Direction {
`,
})
export class AppComponent {
readonly Difficulty = Difficulty;
readonly difficulty = signal<Difficulty>(Difficulty.EASY);
readonly difficulty = signal<keyof Difficulty>('EASY');
readonly direction = signal<keyof Direction | undefined>(undefined);

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

readonly difficultyLabel = computed<string>(() => {
switch (this.difficulty()) {
case Difficulty.EASY:
return Difficulty.EASY;
case Difficulty.NORMAL:
return Difficulty.NORMAL;
}
});
readonly difficultyLabel = computed<string>(() => this.difficulty());

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()}`;
});
}