Is it possible to use a computed
signal to type guard within the template? I am using angular 17.0.0
(without a minor or patch version).
I have two tests within this component, one using a signal isItem
, and one using a function isItemFn
.
isItem
doesn’t seem to allow me to typeguardthis.item
.isItemFn
does allow me to typeguardthis.item
.
Since the value of item
can be one of three things (more to come later), I need a way to apply type guards in the template and I was hoping that signals would help but so far they have not. Is there a way to do this without using a function or a pipe?
@Component({})
export class CompositeChipsDisplayComponent<T> {
@Input() item!: T;
// Doesn't allow for type guards in the template
isItem = computed(() => this.item instanceof CompositeChipsItemDirective);
// Does allow for type guards in the template (but runs too often)
isItemFn(item: unknown): item is CompositeChipsItemDirective {
return item instanceof CompositeChipsItemDirective;
}
}
<!-- Types work within the `if` statement when using a function -->
@if (isItemFn(item)) {
<button class="item">
{{ item.label }}
</button>
}
<!-- Types do not work within the `if` statement when using a signal -->
@if (isItem()) {
<button class="item">
{{ item.label }}
</button>
}