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:
What is Recursive Generic in TypeScript ?
Next article icon

What is Declaration Merging in Typescript ?

Last Updated : 16 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In Typescript, the term "declaration merging" refers to the compiler combining two declarations with the same name into a single definition. Both of the initial declarations are present in this combined definition. It is possible to merge Interfaces, namespaces and enums and so on but classes cannot be merged.

Interface with Interface Merging: In this example, 3 interfaces are declared with the same name 'Student', so all the interfaces are merged. class Student1 implements the merged Interface, it has the properties of all three interfaces.

JavaScript
interface Student {     id: number; }  interface Student {     name: string; }  interface Student {     branch: string; }  class Student1 implements Student {     id = 56545;     name = "sarah";     branch = "CSE"; }  const student = new Student1(); console.log(student); 

Output:

Student1 { id: 56545, name: 'sarah', branch: 'CSE' }

In this example, the same property name is repeated in interfaces, but the datatype is changed. in the first interface property id has type 'number', in the second interface it has type 'string'. Typescript compiler raises error saying "Property 'id' must be of type 'number', but here has type 'string'". here properties do not refer to 'functions'.

JavaScript
interface Student {     id: number; }  interface Student {     // error: Subsequent property declarations     // must have the same type.      // Property 'id' must be of type 'number',      // but here has type 'string'.     id: string;     name: string; }  interface  Student {     branch: string; } 

Output:

error TS2717: Subsequent property declarations must have the same type.  Property 'id' must be of type 'number', but here has type 'string'.        id: string;        ~~    two.ts:252:3            id: number;            ~~      'id' was also declared here.

What if Interfaces have functions declared with the same name but the types of the arguments are different? When the components in the merged interfaces are functions with the same name, they are overloaded, which means that the relevant function will be called based on the kind of input given.

JavaScript
interface Student {     displayId(id: number); }  interface Student {     displayId(id: string); }  const student: Student = {     displayId(id) {         return id;     }, };  console.log(student.displayId("AD54")); console.log(student.displayId(54)); 

Output:

AD54  54

When interfaces with the same signature are combined or merged, the functions which are declared in the recently created interfaces appear at the top of the merged interface, while the functions from the previously created interfaces appear below.

JavaScript
interface Student {   displayId(id: number); }  interface Student {   displayId(id: string); } # precedence in the merged interface  # merged interface interface Student {   displayId(id: string);   displayId(id: number); } 

Output:

With the rest of the theory being the same, there's one exception. functions with string literal types are given greater precedence and hence appear first.

JavaScript
interface Student {     displayId(id: number); }  interface Student {     displayId(id: string);     displayId(id: "AC612"); } interface Student {     displayId(id: "AD645"); }  # Precedence in the merged interface  # merged interface interface Student{     displayId(id: "AC612");     displayId(id: "AD645");     displayId(id: string);     displayId(id: number); } 

Output:


Next Article
What is Recursive Generic in TypeScript ?

S

sarahjane3102
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks-Premier-League-2022

Similar Reads

  • What is Type Annotations in TypeScript ?
    TypeScript Type Annotations allow developers to explicitly define the types of variables, functions, and other elements in the program. They help catch mistakes early by ensuring the right data type is used.They make the code easier to understand and follow.Type Annotations help avoid errors and mak
    3 min read
  • What is TypeScript Definition Manager ?
    What is TypeScript Definition Manager? TypeScript Definition Manager (TSDM) is a type definition manager for TypeScript, the popular JavaScript superset. It is a command line tool (CLI) that helps developers create, maintain, and manage type definitions for TypeScript projects. It is an open-source,
    4 min read
  • What is Type Erasure in TypeScript?
    TypeScript is a very mighty superset of JavaScript, which adds static typing to the language and allows developers to catch errors early on as well as write more maintainable code. This being said a TypeScript type system erases type information at compile time (or during the compilation), a phenome
    4 min read
  • What is the Function type in TypeScript ?
    TypeScript is a JavaScript-based programming language with a typed syntax. It provides improved tools of any size. It adds extra syntax to JavaScript. This helps in facilitating a stronger interaction between you and your editor. It also helps in catching the mistakes well in advance.  It uses type
    3 min read
  • What is Recursive Generic in TypeScript ?
    In TypeScript, a recursive generic is a type that refers to itself within its definition, enabling the creation of data structures or types containing references to the same type within their structure. This capability proves invaluable when dealing with nested or hierarchical data structures like t
    4 min read
  • What are Generics in TypeScript ?
    In this article, we will try to understand all the facts as well as the details associated with Generics in TypeScript along with some coding examples. Generics in TypeScript: Whenever any program or code is written or executed, one major thing one always takes care of which is nothing but making re
    3 min read
  • What are the Modules in Typescript ?
    Modules in TypeScript allow you to organize code into reusable, manageable, and logical units by encapsulating functionalities into separate files. They help avoid global namespace pollution by providing scoped declarations.Modules can be imported and exported, enabling code reuse and better maintai
    4 min read
  • What are triple-slash Directives in TypeScript ?
    Triple-slash directives in TypeScript are special comments that are used to provide instructions to the TypeScript compiler (tsc) or the IDE (Integrated Development Environment) about how to process a TypeScript file. These directives start with three forward slashes (///) and are typically placed a
    6 min read
  • What is namespace in Typescript ?
    In TypeScript, a namespace is a way to organize code logically and prevent naming conflicts between identifiers. It allows developers to group related functionalities, such as interfaces, classes, functions, and variables, within a dedicated scope. Namespaces are particularly useful for structuring
    3 min read
  • What are string literal types in TypeScript ?
    The string literal type was added in TypeScript version 1.8. String literal types work well with union types and type aliases in practice. These properties can be combined to give strings enum-like functionality. The string literal type allows you to specify a set of possible string values for a var
    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