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'.
Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.
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.
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.
One more solution. I use this for row template
export function castTo<T>(): (row) => T {
return (row) => row as T
}
$row = castTo<YourType>();
$row(row).properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With