Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to use Interface with Class in TypeScript ?
Next article icon

How to Cast Object to Interface in TypeScript ?

Last Updated : 23 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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

Syntax:

interface interface_name {}; const objectName = {} const castedInterface = <interface_name> objectName;

Example: The below code example will help you in casting an interface to an object using type assertion.

JavaScript
interface newInterface {     name: string,     desc: string }  const GFG_Obj: any = {     name: "GeeksforGeeks",     desc: "A Computer Science Portal." }  const newCastedInterface = <newInterface> GFG_Obj; 

Using the as keyword

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: "GeeksforGeeks",     desc: "A Computer Science Portal." }  const newCastedInterface = GFG_Obj as newInterface; 

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.

Syntax:

interface interface_name {};  const objectName = {};  const castedInterface: interface_name = {...objectName};

Example: The below code example will explain the use of the spread operator to cast an object into an interface.

JavaScript
interface newInterface {     name: string,     desc: string }  const GFG_Obj: any = {     name: "GeeksforGeeks",     desc: "A Computer Science Portal." }  const newCastedInterface: newInterface = { ...GFG_Obj }; 

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.

Syntax:

interface InterfaceName {     property1: type1;     property2: type2;     // Other properties... }  const objectName: any = {     property1: value1,     property2: value2,     // Other properties... };  const castedObject: InterfaceName = objectName as InterfaceName;

Example: In this example we initializes an object userData with properties name and age, then asserts it as type User using type assertion (as), potentially risking runtime type mismatches.

JavaScript
interface User {     name: string;     age: number; }  const userData: any = {     name: "GeeksForGeeks",     age: 22, };  const user: User = userData as User; 



Next Article
How to use Interface with Class in TypeScript ?

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to Iterate Array of Objects in TypeScript ?
    In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
    4 min read
  • How to Deep Merge Two Objects in TypeScript ?
    Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
    5 min read
  • How to Extract Interface Members in TypeScript ?
    In TypeScript, you can extract interface members (properties and methods) from a class using several approaches. we are going to learn how to extract interface members in TypeScript. Below are the approaches used to extract interface members in TypeScript: Table of Content Manual Extractionimplement
    3 min read
  • How to check interface type in TypeScript ?
    Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
    2 min read
  • How to use Interface with Class in TypeScript ?
    In TypeScript, interfaces define the structure that classes must adhere to, ensuring consistent object shapes and facilitating type-checking. Interfaces declare properties and methods without implementations, serving as contracts for classes to implement.Classes use the implements keyword to adhere
    3 min read
  • How to Define Static Property in TypeScript Interface?
    A static property in a class is a property that belongs to the class itself, rather than to instances of the class. It is shared among all instances of the class and can be accessed without creating an instance of the class. Static properties are defined using the static keyword in front of the prop
    3 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to Define Interfaces for Nested Objects in TypeScript ?
    In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern. Here are step-by-step instructions on how to define interfaces for nested objects in Typ
    2 min read
  • How to Iterate Over Object Properties in TypeScript
    In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object pr
    3 min read
  • How to Cast a JSON Object Inside of TypeScript Class?
    Casting a JSON object to a TypeScript class involves converting a plain JSON object (which lacks methods and proper typing) into an instance of a class that includes all the defined methods and type safety of that class. Types of Objects in TypeScriptPlain Objects: When parsing JSON data using the J
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences