![]() |
In TypeScript, interface and type are used to define the structure of objects and custom types. While interfaces enforce contracts for classes and support multiple inheritance, types offer flexibility for defining complex and reusable type aliases. Each serves distinct use cases. InterfaceIn TypeScript, an interface is a structure that defines the syntax for classes to follow. It specifies properties and methods that an object should have, providing a way to enforce type-checking and ensuring consistent object structure. Syntaxinterface MyInterface {
// Interface properties and methods
} Example: Using Interfaces in TypeScriptIn this example, we defines an interface Person with name and age properties. It then creates a person object following the Person interface
Output "John Doe" // person.name
25 // person.age Type statementType statements in TypeScript define custom types that can represent the structure of objects, primitives, unions, intersections, and more. They allow for creating type aliases, enhancing code readability and reusability by providing descriptive names for complex or existing types. Syntaxtype MyType = {
// Type properties and methods
}
Example: Using Type Aliases in TypeScriptIn this example, we defines a Point type with x and y properties. It creates a point object conforming to the Point type and prints its x and y values
Output: 10 // point.x
20 // point.y
Difference between Interface and type Statements
In TypeScript, interface and type are powerful tools for defining object structures and custom types. Interfaces enforce specific contracts for classes and support multiple inheritance, promoting consistent object structure. Types offer flexibility in defining complex and reusable type aliases, enhancing code readability and maintainability. Both are crucial for ensuring type safety and clarity in TypeScript code, each serving distinct but complementary purposes. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |