#Using Signals hurts type safety in templates

6 messages · Page 1 of 1 (latest)

rotund mango
#

Consider the following component (https://stackblitz.com/edit/angular-17-starter-project-yuqjrq?file=src%2Fmain.ts)

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
     @if(item()) {
        <div>{{item().id}}</div> // <-- this will cause an error
    } @else {
        <div>No item</div>
    }
  `,
})
export class App {
  item = signal<Item | null>(null);
}

interface Item {
  id: string;  
}

This will result in the following error:
Object is possibly 'null'.

The TS compiler warns item() may be null, since reading the signal is done via a function call.

Can someone recommend a type-safe way to access a signal in a component template?

An angular-cli project based on @angular/animations, @angular/common, @angular/compiler, @angular/core, @angular/forms, @angular/platform-browser, @angular/platform-browser-dynamic, @angular/router, core-js, rxjs, tslib and zone.js

#

Using Signals hurts Types safety in templates

#

Using Signals hurts type safety in templates

errant juniper
#
@if (item(); as i) {
  <div>{{ i.id }}</div> 
rotund mango
#

oh cool, thanks!