4

我有一个像

import { Component } from '@angular/core';

interface ItemBaseType {
   foo: boolean;
}

interface ItemType extends ItemBaseType {
   bar: boolean;
}

@Component({
  selector: 'ac-foo',
  template: `<div *ngIf="item.bar">Hello</div>`,
})
export class FooComponent {
   public item: ItemType;
}

我在 Angular 9 应用程序上启用了 fullTemplateTypeCheck 和 strictTemplatesng serve ,它在运行时引发异常:

类型“ItemBaseType”上不存在属性“bar”。

bar存在于ItemType.

出了什么问题?

4

2 回答 2

1

在这种情况下,您可以使用 item?.bar。我希望它有所帮助。

于 2020-04-23T08:13:47.803 回答
0

使用管道检查我的模板 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.
}
于 2021-10-08T08:54:00.190 回答