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