https://angular.love/en/angular-template-let-variable-hot-or-not #263
Replies: 1 comment
-
Recently I've experienced Type Narrowing problem in signal-based component and I find Im introducing export type TStatus<TPayload = any, TError = never> =
| {
status: 'LOADING';
}
| {
status: 'SUCCESS';
payload: TPayload;
}
| {
status: 'ERROR';
reason: TError;
}; I want to use it in @Component({
selector: 'my-status',
standalone: true,
templateUrl: './status.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StatusComponent {
public readonly result = input.required<TStatus<{ hasAccess: boolean }, string>>();
} @switch (result().status) {
@case ("LOADING") {
Loading...
}
@case ("SUCCESS") {
Has access: {{ result().payload.hasAccess }}
}
@case ("ERROR") {
Something went wrong: {{ result().reason }}
}
} The most important thing is that I want But still, the code above produces an error As it turned out, it is because type narrowing doesn't work with signals and the only way to make it work again is to "unpack" signal's value. You can do it with Working version looks like this: @let resultValue = result();
@switch (resultValue.status) {
@case ("LOADING") {
Loading...
}
@case ("SUCCESS") {
Has access: {{ resultValue.payload.hasAccess }}
}
@case ("ERROR") {
Something went wrong: {{ resultValue.reason }}
}
} Maybe in the future type narrowing will be supported in signal-based components but for now this is a solid workaround. Please correct me and let me know, if you are aware of better way of solving this issue. Cheers! |
Beta Was this translation helpful? Give feedback.
-
https://angular.love/en/angular-template-let-variable-hot-or-not
Angular.love - a place for all Angular enthusiasts created to inspire and educate.
https://angular.love/en/angular-template-let-variable-hot-or-not
Beta Was this translation helpful? Give feedback.
All reactions