#control flow, signals, and typescript type guards

2 messages · Page 1 of 1 (latest)

normal mirage
#

In the next example I'm using a signal<undefined|T> and using an @if block as a type guard:

@Component({
  selector: 'app-root',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
  <button (click)="toggle()">toggle state</button>

  @if(state(); as user) {
    <pre>{{ state().name}}</pre>
    <pre>{{ user.name}}</pre>
  }
  `,
})
export class AppComponent {
  user = { name: 'Sebs' };
  state = signal<undefined|typeof this.user>(undefined);
  toggle() {
    this.state.update(i => i ? undefined : this.user);
  }
}
```but this generates an error```text
✘ [ERROR] NG2: Object is possibly 'undefined'. [plugin angular-compiler]
    src/app/app.component.ts:21:20:
      21 │     <pre>{{ state().name}}</pre>
         │                     ~~~~

Is this a bug/regression?
Why when using the signal value directly it errors, but when using a reference doesn't?

I couldn't find anything in the docs or github issues and discussions about this.

hollow lichen