Different ways to convert any type to objects in Angular example


In this post, We are going to convert or cast any type in typescript to object with examples in Angular.

This tutorials covers an following things

  • How to change variable type in typescript
  • Convert any type to string or number in Angular
  • Parse any type to Interface or classin Angular

In typescript, There is no type casting,but we have type assertions. So There are two approaches to cast any object to different data types.

  • use generics <>
  • as keyword

using generic <> symbol

Type assertion is an way telling to compiler about an variable as an type instead of infer the value.

For example, if we declare an variable of type any with numeric value.

when we assigned this to another variable, we are telling compiler and parse this as number.

let numb: any = 111; 
let id = <number> numb; 
console.log(typeof(id)); //Output: number

And other way using as keyword

as 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 keyword is 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 in typescript.

 display(anyvalue: any) {
    this.str = <string> anyvalue;
  }

We can also use as 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 into interface or object into Angular Class (Type)

Sometimes, API returns data of any type, So you need to convert to interface or class in angular we can do with as keyword with type assertion

let emp:Employee= anytype as Employee

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;
  }
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.