简体   繁体   English

Angular/ TypeScript - 如何在 HTML 文件中键入铸件?

[英]Angular/ TypeScript - How to Type casting in HTML file?

I have a TypeScript interfaces:我有一个 TypeScript 接口:

export interface iA {
  name: string;
}
export interface iB {
  size: number;
}
export interface iX {
  id: number;
  data: iA | iB;
}

Then in one of my Angular component class I'm using interface iX:然后在我的 Angular 组件 class 之一中,我正在使用接口 iX:

// example.component.ts
class ExampleComplnent {
  public item: iX = {
    id: 1,
    data: { name: 'test' }
  }
}
<!-- example.component.html -->
<div>{{ item.data.name }}</div>

This will throw an error: Propery 'name' not exist on type 'iB' .这将抛出一个错误: Propery 'name' not exist on type 'iB'

I know that in a TypeScript file I can use casting like this:我知道在 TypeScript 文件中我可以像这样使用强制转换:

const name = (item.data as iA).name;

But how can I make casting on the HTML side?但是如何在 HTML 一侧进行铸造?

I also want to mention that in my code I'm validating that item.data is of type iA , not of type iB .我还想提一下,在我的代码中,我正在验证item.dataiA类型,而不是iB类型。 So I'm sure it have the property 'name'.所以我确定它具有“名称”属性。

As @PoulKruijt mentioned, Angular doesn't provide a way to cast using as in the component's template.正如@PoulKruijt 提到的,Angular 没有提供在组件模板中使用as的方法。 However, you can consider using $any() , which cast to any.但是,您可以考虑使用强制转换为任意的$any() It will suppress the error but it is not type-safe.它将抑制错误,但它不是类型安全的。 Refer to this: https://angular.io/guide/template-syntax#the-any-type-cast-function参考这个: https://angular.io/guide/template-syntax#the-any-type-cast-function

Unfortunately that's not possible.不幸的是,这是不可能的。 It depends on your implementation what the best solution is.这取决于您的实施,最好的解决方案是什么。 You can use generics:您可以使用 generics:

export interface iA {
  name: string;
}
export interface iB {
  size: number;
}
export interface iX<T extends (iA | iB)> {
  id: number;
  data: T;
}

export class ExampleComponent {
  item: iX<iA>;
}

You can use some method call from the template which asserts the type:您可以使用模板中的一些方法调用来断言类型:

@Component({
  selector: 'my-app',
  template: '{{ getIaData(item)?.name }}',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  item: iX;

  getIaData(ix: iX): iA | undefined {
    return this.isIa(ix.data) ? ix.data : void 0; 
  }

  isIa(data: iA | iB): data is iA {
    return !!(data as iA).name;
  }
}

working example 工作示例

and I'm sure there are more.我敢肯定还有更多。 But like I said, it depends on where you get the item from and how and where it is defined但就像我说的,这取决于你从哪里获得item以及如何以及在哪里定义它

One more solution.另一种解决方案。 I use this for row template我将此用于行模板

  1. Create util function创建工具 function
export function castTo<T>(): (row) => T {
  return (row) => row as T
}
  1. Call function in component在组件中调用 function
$row = castTo<YourType>();
  1. Use in template在模板中使用
$row(row).properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM