乐闻世界logo
搜索文章和话题

How can you declare and use an interface in TypeScript?

1个答案

1

Declaring Interfaces

In TypeScript, declaring an interface is straightforward. You use the interface keyword, followed by the interface name and curly braces, where you define the structure. For example, if we need an interface describing a user, we can declare it as:

typescript
interface User { username: string; password: string; age?: number; // optional property }

In this User interface, we define two required properties: username and password, both of string type. We also define an optional property age, indicating that not all users need to provide an age.

Using Interfaces

Once the interface is defined, you can use it in functions or classes to type-annotate objects. For example, you can write a function that accepts a User-typed object:

typescript
function login(user: User) { console.log(`Logging in user: ${user.username}`); // With the interface, we can be confident that the user object includes username and password properties }

Interfaces and Classes

In TypeScript, classes can implement interfaces, which requires the class to adhere to the structure defined by the interface. This is achieved using the implements keyword.

typescript
class Admin implements User { username: string; password: string; age?: number; constructor(username: string, password: string, age?: number) { this.username = username; this.password = password; this.age = age; } manageUsers() { console.log('Managing users'); } }

Here, the Admin class implements the User interface, so it must include username and password properties, optionally including age. Additionally, it can have its own methods, such as manageUsers.

Interface Inheritance

Interfaces can also inherit from each other, allowing you to create a more specific version from one interface.

typescript
interface AdminUser extends User { permissions: string[]; } function createAdmin(user: AdminUser) { console.log(`Creating admin: ${user.username} with permissions: ${user.permissions.join(', ')}`); }

In this example, the AdminUser interface inherits from the User interface and adds a new property permissions, which is a string array representing the user's permissions.

Summary

By using interfaces, TypeScript provides a powerful way to ensure type safety and structural consistency in code. The use of interfaces promotes good programming practices, such as encapsulation and abstraction, and also aids in code maintenance and extensibility.

2024年7月29日 13:53 回复

你的答案