Skip to content

Exhaustive @switch type-checking #52107

@cexbrayat

Description

@cexbrayat

Which @angular/* package(s) are relevant/related to the feature request?

common

Description

I think it would be a great addition to the type-safety of templates if @switch were checked to be exhaustive.

Currently, if you have a field with 3 possible values:

type UserType = 'admin' | 'logged' | 'anonymous'

and then use a @switch in the template:

@switch (userType) {
  @case ('admin') {
    Hello admin
  }
  @case ('logged') {
    Hello user
  }
}

the template compiles just fine, whereas the 'anonymous' case is not covered.

Proposed solution

It would be great to get a compiler error if a case is missing (when no default is provided of course).

TypeScript would complain about a missing case, if the switch was used to return a value in a function:

function s(userType: UserType): boolean {
  switch (userType) {
    case 'admin': return true;
    case 'logged': return true;
  }
}

The generated TCB could maybe be code along those lines instead of a "simple" switch?

Alternatives considered

I don't think we can work around that easily?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: coreIssues related to the framework runtimecompiler: template type-checkingcore: control flowIssues related to the built-in control flow (@if, @for, @switch)featureIssue that requests a new feature

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions