In TypeScript, an
interface defines the structure of an object. It specifies the names and types of properties that an object must have. To define an interface, you use the `interface` keyword, followed by the interface name and the property definitions enclosed in braces `{ }`. Here's an example:
interface Person {
firstName: string;
lastName: string;
age: number;
email?: string;
}
In this example, we define an interface called `Person` that has four properties: `firstName` and `lastName`, both of type `string`, `age` of type `number`, and an optional property `email` of type `string`.
To use an interface, you can define an object that conforms to its structure:
let person: Person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "john.doe@example.com"
};
Here, we define an object `person` that conforms to the `Person` interface. It has properties `firstName`, `lastName`, `age`, and `email`.
If an object doesn't have all the required properties defined in an interface, TypeScript will generate an error:
let person: Person = {
firstName: "John",
age: 30 // Error: Property 'lastName' is missing
};
You can also use interfaces as types for function parameters and return values:
function getFullName(person: Person): string {
return `${person.firstName} ${person.lastName}`;
}
Here, the `getFullName` function takes a parameter of type `Person` and returns a string.
Interfaces can also extend other interfaces and define optional and readonly properties, among other things.