How to use the as keyword In Typescript

We can use the as keyword to cast the object into an interface by using the below syntax.

Syntax:

interface interface_name {};
const objectName = {};
const castedInterface = objectName as interface_name;

Example: The below example is an practical implementation of casting an object into an interface using the as keyword.

Javascript
interface newInterface {
    name: string,
    desc: string
}

const GFG_Obj: any = {
    name: "w3wiki",
    desc: "A Computer Science Portal."
}

const newCastedInterface = GFG_Obj as newInterface;

How to Cast Object to Interface in TypeScript ?

In TypeScript, sometimes you need to cast an object into an interface to perform some tasks.

There are many ways available in TypeScript that can be used to cast an object into an interface as listed below:

Table of Content

  • Using the angle bracket syntax
  • Using the as keyword
  • Using the spread operator
  • Using Type Assertion with Object Properties

Similar Reads

Using the angle bracket syntax

You can use the type assertion to cast the object into an interface by defining an interface and using the name of that interface inside angled brackets(<>)....

Using the as keyword

We can use the as keyword to cast the object into an interface by using the below syntax....

Using the spread operator

The spread operator syntax can also be used to cast an object into an interface by simply specifying the type of the new object as interface and assign the value of the object using spread operator syntax as shown in below syntax....

Using Type Assertion with Object Properties

You can also cast an object to an interface by directly assigning it to a variable of the interface type using type assertion. This method is particularly useful when you have an object with properties that match those defined in the interface....