Angular/ TypeScript - 如何在 HTML 文件中进行类型转换?

Gil*_*ain 10 casting typescript angular

我有一个 TypeScript 接口:

export interface iA {
  name: string;
}
export interface iB {
  size: number;
}
export interface iX {
  id: number;
  data: iA | iB;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 Angular 组件类之一中,我使用接口 iX:

// example.component.ts
class ExampleComplnent {
  public item: iX = {
    id: 1,
    data: { name: 'test' }
  }
}
Run Code Online (Sandbox Code Playgroud)
export interface iA {
  name: string;
}
export interface iB {
  size: number;
}
export interface iX {
  id: number;
  data: iA | iB;
}
Run Code Online (Sandbox Code Playgroud)

这将引发错误:Propery 'name' not exist on type 'iB'

我知道在 TypeScript 文件中我可以像这样使用转换:

const name = (item.data as iA).name;
Run Code Online (Sandbox Code Playgroud)

但是如何在 HTML 端进行投射呢?

我还想提一下,在我的代码中,我验证的item.data是 type iA,而不是 type iB。所以我确信它有属性“名称”。

kli*_*mir 10

还有一种解决方案。我用它作为行模板

  1. 创建效用函数
export function castTo<T>(): (row) => T {
  return (row) => row as T
}
Run Code Online (Sandbox Code Playgroud)
  1. 调用组件中的函数
$row = castTo<YourType>();
Run Code Online (Sandbox Code Playgroud)
  1. 在模板中使用
$row(row).properties
Run Code Online (Sandbox Code Playgroud)

  • 这不是高性能的 (3认同)

Abo*_*odz 5

as正如 @PoulKruijt 提到的,Angular 没有提供在组件模板中使用的方法。但是,您可以考虑使用$any(),它将强制转换为 any。它会抑制错误,但它不是类型安全的。请参阅:https: //angular.io/guide/template-syntax#the-any-type-cast-function


Pie*_*Duc 3

不幸的是,这是不可能的。这取决于您的实施,最佳解决方案是什么。您可以使用泛型:

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>;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用模板中的一些方法调用来断言类型:

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

工作示例

我确信还有更多。但就像我说的,这取决于你item从哪里获得以及它是如何定义的以及在哪里定义的