TypeScript Interface vs Type Statements
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.
Interface
In 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.
Syntax
interface MyInterface {
// Interface properties and methods
}
Example: Using Interfaces in TypeScript
In this example, we defines an interface Person with name and age properties. It then creates a person object following the Person interface
// Interface.ts
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John Doe",
age: 25,
};
console.log(person.name);
console.log(person.age);
Output
"John Doe" // person.name
25 // person.age
Type statement
Type 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.
Syntax
type MyType = {
// Type properties and methods
}
Example: Using Type Aliases in TypeScript
In 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
// type.ts
type Point = {
x: number;
y: number;
};
const point: Point = {
x: 10,
y: 20,
};
console.log(point.x);
console.log(point.y);
Output:
10 // point.x
20 // point.y
Difference between Interface and type Statements
Type | Interface | |
---|---|---|
Purpose |
|
|
Syntax |
|
|
Usage |
|
|
Implementation |
|
|
Extensibility |
|
|
Polymorphism |
|
|
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.