使用管道检查我的模板 TypeSafe 铸造答案:
import { Pipe, PipeTransform } from '@angular/core';
/**
* Cast super type into type using generics
* Return Type obtained by optional @param type OR assignment type.
*/
@Pipe({ name: 'cast' })
export class CastPipe implements PipeTransform {
/**
* Cast (S: SuperType) into (T: Type) using @Generics.
* @param value (S: SuperType) obtained from input type.
* @optional @param type (T CastingType)
* @returns (T: Type) obtained by optional @param type OR assignment type.
*/
transform<S, T extends S>(value: S, type?: { new (): T }): T {
return <T>value;
}
}
用法:
import { Component } from '@angular/core';
interface ItemBaseType {
foo: boolean;
}
interface ItemType extends ItemBaseType {
bar: boolean;
}
@Component({
selector: 'ac-foo',
template: `<div *ngIf="item.bar | cast: ItemType">Hello</div>`,
})
export class FooComponent {
// public item: ItemType; // Your case should be ItemBaseType
// Expected your case reference to supertype that doesn’t directly contains bar property item refer to super type.
public item: ItemBaseType;
ItemType = ItemType; // ItemType alias for template reference.
}