Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a TypeScript interfaces:

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:

// 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'.

I know that in a TypeScript file I can use casting like this:

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

But how can I make casting on the HTML side?

I also want to mention that in my code I'm validating that item.data is of type iA, not of type iB. So I'm sure it have the property 'name'.

like image 968
Gil Epshtain Avatar asked Jul 20 '20 08:07

Gil Epshtain


People also ask

Can you type cast in TypeScript?

Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.

How do I cast objects in TypeScript?

If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.

How do I change a type of variable in TypeScript?

Solution. You cannot change a variable's type in TypeScript, that's just the opposite TS was made for. Instead, you can declare a variable as "any", which would be equivalent to a classic "var" variable in JS, untyped. Once a variable is declared, you will not be able to retype it.


1 Answers

One more solution. I use this for row template

  1. Create utility function
export function castTo<T>(): (row) => T {
  return (row) => row as T
}
  1. Call function in component
$row = castTo<YourType>();
  1. Use in template
$row(row).properties
like image 56
klivladimir Avatar answered Sep 23 '22 19:09

klivladimir