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

What is an Interface in TypeScript?

2月7日 00:01

In TypeScript, an interface (Interface) is a key construct for defining the structure of an object, specifying the properties and methods it must include along with their types. Interfaces are primarily used for type checking, allowing developers to ensure that code adheres to specific structural and type constraints during implementation.

Interfaces can declare properties and methods, but they are abstract and do not include concrete implementations. Any class implementing the interface must conform to the structure defined by the interface.

Example:

typescript
interface Person { name: string; age: number; greet(phrase: string): void; } class User implements Person { name: string; age: number; constructor(n: string, a: number) { this.name = n; this.age = a; } greet(phrase: string) { console.log(phrase + ' ' + this.name); } }

In the above code, the Person interface specifies that a class must have two properties, name and age, and a greet method. The User class implements this interface, so it must provide concrete implementations for these properties and methods. This mechanism helps ensure consistency in data structures and behavior within TypeScript.

标签:TypeScript