How can I achieve exhaustive typechecking in `@switch` blocks in Angular templates ?

I can do

type Status = | { kind: 'idle' } | { kind: 'loading' } | { kind: 'success'; data: string } | { kind: 'error'; message: string }; export class DemoComponent { state: Status = { kind: 'idle' }; assertNever(value: never): never { throw new Error('Unexpected value: ' + value); } }

and

@switch (state.kind) { @case ('idle') { <p>Idle</p> } @case ('loading') { <p>Loading…</p> } @case ('success') { <!-- state is narrowed --> <p>Result: {{ state.data }}</p> } @case ('error') { <!-- state is narrowed --> <p>Error: {{ state.message }}</p> } @default { {{ assertNever(state) }} } }

But this kind of verbose. Is there an alternative ?

Matthieu Riegler's user avatar

In v21.2 Angular added support for exaustive typechecking in @switch blocks with the @default never; statement:

No need to define a method in the component now.

@switch (state.kind) { @case ('idle') { <p>Idle</p> } @case ('loading') { <p>Loading…</p> } @case ('success') { <!-- state is narrowed --> <p>Result: {{ state.data }}</p> } @case ('error') { <!-- state is narrowed --> <p>Error: {{ state.message }}</p> } @default never; <!-- Enables exhaustive typecheking here --> }

Matthieu Riegler's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.