What is an Interface in TypeScript?

In TypeScript, an interface is a structure that defines the shape of an object. It specifies the names and types of properties that an object should have, and allows you to enforce certain constraints on the values of those properties. For example, you might use an interface to define the structure of a Person object, with properties like name and age.

// Define a "Person" interface
interface Person {
name: string;
age: number;
}
// Create a "Person" object that adheres to the "Person" interface
let person: Person = {
name: 'John Doe',
age: 32
};

Interfaces are a powerful tool in TypeScript because they allow you to write code that is more abstract and flexible. For example, you can define a function that takes an object as an argument, but only allows objects that conform to a specific interface to be passed in. This allows you to write code that is more generic and reusable.

// Define a "Person" interface
interface Person {
name: string;
age: number;
}
// Define a function that takes a "Person" object as an argument
function greet(person: Person) {
console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}
// Create a "Person" object that adheres to the "Person" interface
let person: Person = {
name: 'John Doe',
age: 32
};
// Call the "greet" function and pass in the "Person" object
greet(person); // Output: "Hello, John Doe! You are 32 years old."

In summary, an interface in TypeScript allows you to define the structure of an object, and to enforce certain constraints on the values of its properties. This can help you write more abstract and flexible code that is easier to understand and maintain.


December 05, 2022
198