How to convert any type to object in Angular Code example
Learn to convert or cast any type in typescript to an object with examples in Angular.
This tutorial covers the following things
- How to change variable type in typescript
- Convert any type to string or number in Angular.
- Parse any type of Interface or class in Angular.
In typescript, There is no typecasting, but we have type assertions. So There are two approaches to casting any object to different data types.
- use generics
<>
- as keyword
Convert any type to object using Type assertion(generic) symbol
Type assertion is a way of telling the compiler about a variable as a type instead of inferring the value.
For example, declare a variable of type any
with a numeric value.
when we assigned this to another variable, we are telling the compiler and parse this as a number.
let numb: any = 111;
let id = <number> numb;
console.log(typeof(id)); //Output: number
And another way to use it as a keyword.
Convert any type to an object using as a keyword
let numb: any = 111;
let id = numb as number;
console.log(typeof(id)); //Output: number
Generics<>
will not work in files with TSX files, as the keyword is the preferred way to cast from one type to another type.
How to convert any type to string in typescript?
In the following example, variable of type any is parsed into string variable using generics<string>
in typescript.
display(anyvalue: any) {
this.str = <string> anyvalue;
}
We can also use it as a keyword which is preferable in typescript.
display(anyvalue: any) {
this.str = anyvalue as string;
}
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
str = 'hello';
constructor() {
this.display(123);
}
display(anyvalue: any) {
this.str = <string> anyvalue;
}
}
How to cast any interface or object into Angular Class (Type)
Sometimes, API returns data of any type, So you need to convert it to interface or class in angular. we can do this with the as
keyword with a type assertion
let emp:Employee= any type as Employee
The employee is an interface in typescript with id and name fields.
We can also do using generics as seen below.
let emp:Employee= <Employee> anytype
Complete example below
import { Component, VERSION } from '@angular/core';
import { Employee } from '../employee';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employee: Employee;
constructor() {
this.display({
id: 1,
name: 'john'
});
}
display(anyvalue: any) {
this.employee = anyvalue as Employee;
}
}