What are TypeScript Interfaces?
TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.
- Allow for optional and read-only properties for flexibility and immutability.
- Enable interface inheritance to create reusable and extendable object structures.
interface User {
username: string;
email: string;
}
const newUser: User = {
username: "john_doe",
email: "john@example.com"
};
console.log(`User: ${newUser.username}, Email: ${newUser.email}`);
- The User interface specifies that any object of type User should have username and email properties, both of which are strings.
- The newUser object adheres to the User interface by providing the required properties with appropriate string values.
Output:
User: john_doe, Email: john@example.com
Properties of Interfaces
1. Extending Properties
Interfaces in TypeScript can extend other interfaces, allowing for property reuse and additional customization.
interface For_Array {
var1: string;
}
interface For_List extends For_Array {
var2: string;
}
- The For_List interface extends For_Array, inheriting the var1 property while introducing a new property var2.
- This allows a hierarchical design of interfaces, promoting modularity and reuse.
2. Read-Only Properties
Properties marked as readonly cannot be modified after their initial assignment.
Example:
interface For_class {
readonly name: string;
id: number;
}
- The name property in the For_class interface is immutable, ensuring its value remains constant.
- This is ideal for scenarios where certain object attributes must remain unchanged, such as IDs or constants.
3. Optional Properties
The ? symbol makes properties optional, adding flexibility to object definitions.
interface For_function {
(key: string, value?: string): void;
}
- The value parameter is optional, meaning functions can be defined with or without it.
- This reduces constraints on function parameters, accommodating varying use cases while maintaining type safety.
More Example of TypeScript Interfaces
Defining a Product Interface
interface Product {
id: number;
name: string;
price: number;
description?: string; // Optional property
}
const item: Product = {
id: 1,
name: "Laptop",
price: 999.99
};
console.log(`Product: ${item.name}, Price: $${item.price}`);
- The Product interface specifies that any object of type Product should have id, name, and price properties as required, and an optional description property.
- The item object adheres to the Product interface by providing the required properties with appropriate values.
Output:
Product: Laptop, Price: $999.99
Implementing an Interface in a Class
interface Animal {
name: string;
sound: () => void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sound() {
console.log(`${this.name} says: Woof!`);
}
}
const myDog = new Dog("Buddy");
myDog.sound();
- The Animal interface defines a structure with a name property and a sound method.
- The Dog class implements the Animal interface, providing concrete implementations for the name property and the sound method.
Output:
Buddy says: Woof!
Best Practices of Using TypeScript Interfaces
- Use Interfaces to Define Object Shapes: Interfaces clearly define the structure of objects, enhancing code readability and maintainability.
- Leverage Optional and Readonly Properties: Utilize optional (?) and readonly properties to express flexibility and immutability in your data models.
- Prefer Interfaces Over Type Aliases for Object Types: Interfaces are extendable and provide better tooling support for defining object types.
- Extend Interfaces for Reusability: Create base interfaces and extend them to build complex types, promoting code reuse and consistency.
What are TypeScript Interfaces – FAQs
What is the difference between an interface and a type alias in TypeScript?
Interfaces are best for defining object shapes and can be extended or implemented by classes, while type aliases are more versatile, capable of representing primitives, unions, and other types.
Can interfaces have optional properties?
Yes, by appending a question mark (?) to the property name, indicating that the property is optional.
How do you make properties read-only in an interface?
Use the readonly modifier before the property name to prevent reassignment after the initial value is set.
Can interfaces extend multiple interfaces?
Yes, interfaces can extend multiple interfaces, allowing for the combination of multiple types into a single interface.
Are interfaces only for object types in TypeScript?
Primarily, yes. Interfaces are used to define the shape of objects, including the types of their properties and methods.