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 check interface type in TypeScript ?
Next article icon

How to Extract Interface Members in TypeScript ?

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

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 Extraction
  • implements Keyword
  • type Keyword with typeof
  • Using Utility Types

Approach 1: Manual Extraction

You manually declare an interface and list the members that you want to extract.

Example: In this example, an interface named MyInterface is manually declared to match the structure of the MyClass. The interface includes a property property1 of type string a method method1 with no parameters and a return type of void. This manual extraction allows for explicit control over the interface members.

JavaScript
class MyClass {     public property1: string = "Hello";     public method1(): void {         console.log("Method 1 called");     } }  // Manually extract interface interface MyInterface {     property1: string;     method1(): void; }  const myInstance: MyInterface = new MyClass();  console.log(myInstance.property1); // Output: Hello myInstance.method1(); // Output: Method 1 called 

Output:

Hello Method 1 called

Approach 2: implements Keyword

You use the implements keyword to create an interface that matches the structure of the class.

Example: Using the implements keyword, the class MyClass explicitly states that it adheres to the MyInterface. The MyInterface interface lists the expected members (property1 and method1). This approach enforces that MyClass must implement all the members declared in MyInterface, providing a clear contract between the class and the interface.

JavaScript
class MyClass implements MyInterface {     public property1: string = "World";     public method1(): void {         console.log("Method 1 called");     } }  // Extracted interface interface MyInterface {     property1: string;     method1(): void; }  const myInstance: MyInterface = new MyClass();  console.log(myInstance.property1); // Output: World myInstance.method1(); // Output: Method 1 called 

Output:

World Method 1 called

Approach 3: type Keyword with typeof

You use the type keyword and the typeof operator to automatically generate an interface based on the class.

Example: In this TypeScript example, we define a Dog class with properties (name and age) and a method (bark). To extract an interface that includes both the static and instance sides of the class, we use InstanceType<typeof Dog>.

JavaScript
class Dog {     constructor(public name: string, public age: number) { }      bark(): void {         console.log('Woof! Woof!');     } }  // Extracting interface using  // InstanceType and typeof type DogInterface = InstanceType<typeof Dog>;  const myDog = new Dog('Buddy', 3);  const myDogTyped: DogInterface = myDog;  // Now you can use the interface members console.log(myDogTyped.name); console.log(myDogTyped.age); 

Output:

Buddy 3

Approach 4: Using Utility Types

While TypeScript utility types offer powerful transformations on types, classes don't support structural typing directly. Thus, extracting members from a class using utility types like Pick isn't feasible. However, you can achieve similar functionality by manually declaring an interface that mirrors the structure of the class.

Example:

JavaScript
// Define an interface that mirrors the structure of MyClass interface MyInterface {     property1: string;     method1(): void; }  // Implement the interface in MyClass class MyClass implements MyInterface {     public property1: string = "Hello";     public method1(): void {         console.log("Method 1 called");     } }  // Now you can use instances of MyClass wherever MyInterface is expected const myInstance: MyInterface = new MyClass();  // Access properties and methods through the interface console.log(myInstance.property1);  myInstance.method1();  

Output:

Hello  Method 1 called

Next Article
How to check interface type in TypeScript ?

A

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

Similar Reads

  • 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 syntaxUsing the as keywordUsing the spread operatorU
    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 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 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 Map Elements in TypeScript ?
    In TypeScript, iterating over the Map elements means accessing and traversing over the key-value pairs of the Map Data Structure. The Map is nothing but the iterative interface in TypeScript. We can iterate over the Map elements in TypeScript using various approaches that include inbuilt methods and
    4 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 Arrays of Generic Interfaces in TypeScript ?
    In TypeScript, managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility. There are various methods for constructing arrays of generic interface
    3 min read
  • How to Extend an Interface from a class in TypeScript ?
    In this article, we will try to understand how we to extend an interface from a class in TypeScript with the help of certain coding examples. Let us first quickly understand how we can create a class as well as an interface in TypeScript using the following mentioned syntaxes: Syntax:  This is the s
    3 min read
  • How to Require a Specific String in TypeScript Interface ?
    To require a specific string in the TypeScript interface, we have different approaches. In this article, we are going to learn how to require a specific string in the TypeScript interface. Below are the approaches used to require a specific string in the TypeScript interface: Table of Content Using
    2 min read
  • How to Iterate Over Characters of a String in TypeScript ?
    In Typescript, iterating over the characters of the string can be done using various approaches. We can use loops, split() method approach to iterate over the characters. Below are the possible approaches: Table of Content Using for LoopUsing forEach() methodUsing split() methodUsing for...of LoopUs
    2 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