Introduction
Interfaces in TypeScript are a powerful way to define the structure of an object. They allow you to specify the types of properties and methods that an object must have, providing a clear contract for the shape of the data. This helps in maintaining type safety and improving code readability.
Key Concepts
- Defining an Interface: An interface is defined using the
interfacekeyword followed by the name of the interface. - Optional Properties: Properties can be marked as optional using the
?symbol. - Readonly Properties: Properties can be marked as readonly using the
readonlykeyword. - Function Types: Interfaces can also define the types of functions.
- Extending Interfaces: Interfaces can extend other interfaces, allowing for the reuse of properties and methods.
Defining an Interface
An interface is defined using the interface keyword. Here is a simple example:
In this example, the Person interface defines an object with two properties: name (a string) and age (a number).
Optional Properties
Properties can be marked as optional using the ? symbol. This means that the property may or may not be present in the object.
In this example, the age property is optional.
Readonly Properties
Properties can be marked as readonly using the readonly keyword. This means that the property cannot be changed after the object is created.
In this example, the id property is readonly.
Function Types
Interfaces can also define the types of functions. Here is an example:
In this example, the SearchFunc interface defines a function that takes two string parameters and returns a boolean.
Extending Interfaces
Interfaces can extend other interfaces, allowing for the reuse of properties and methods.
interface Person {
name: string;
age?: number;
}
interface Employee extends Person {
employeeId: number;
}In this example, the Employee interface extends the Person interface, adding an employeeId property.
Practical Examples
Example 1: Basic Interface
interface Car {
make: string;
model: string;
year: number;
}
const myCar: Car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
console.log(myCar);Example 2: Optional and Readonly Properties
interface Book {
readonly isbn: string;
title: string;
author: string;
publishedYear?: number;
}
const myBook: Book = {
isbn: "123-456-789",
title: "TypeScript Basics",
author: "John Doe"
};
console.log(myBook);Example 3: Function Types
interface StringValidator {
(input: string): boolean;
}
const isValidEmail: StringValidator = (email) => {
const re = /\S+@\S+\.\S+/;
return re.test(email);
};
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid-email")); // falseExample 4: Extending Interfaces
interface Animal {
name: string;
age: number;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = {
name: "Buddy",
age: 3,
breed: "Golden Retriever"
};
console.log(myDog);Exercises
Exercise 1: Define an Interface
Define an interface Student with the following properties:
id(number, readonly)name(string)age(number, optional)courses(array of strings)
Create an object student1 that adheres to the Student interface.
Solution
interface Student {
readonly id: number;
name: string;
age?: number;
courses: string[];
}
const student1: Student = {
id: 1,
name: "Alice",
courses: ["Math", "Science"]
};
console.log(student1);Exercise 2: Extend an Interface
Define an interface Teacher that extends the Person interface with an additional property subject (string).
Create an object teacher1 that adheres to the Teacher interface.
Solution
interface Person {
name: string;
age?: number;
}
interface Teacher extends Person {
subject: string;
}
const teacher1: Teacher = {
name: "Mr. Smith",
age: 40,
subject: "Mathematics"
};
console.log(teacher1);Conclusion
In this section, we have learned about interfaces in TypeScript, including how to define them, use optional and readonly properties, define function types, and extend interfaces. Interfaces are a powerful feature in TypeScript that help in defining the structure of objects and ensuring type safety. In the next section, we will explore classes in TypeScript.
TypeScript Course
Module 1: Introduction to TypeScript
- What is TypeScript?
- Setting Up the TypeScript Environment
- Basic Types
- Type Annotations
- Compiling TypeScript
Module 2: Working with Types
Module 3: Advanced Types
Module 4: Functions and Modules
Module 5: Asynchronous Programming
Module 6: Tooling and Best Practices
- Linting and Formatting
- Testing TypeScript Code
- TypeScript with Webpack
- TypeScript with React
- Best Practices
