TypeScript Interface Definition and Properties
In TypeScript, interfaces are a syntax structure used to define the shape of objects. They provide a way to describe the properties and methods that an object should possess. Interfaces are a fundamental concept in TypeScript because they allow us to catch errors in code at compile time, thereby enhancing code reliability and maintainability.
Below is a simple example defining an interface named Person:
interface Person {
name: string;
age: number;
speak(): void;
}
In this example, the Person interface defines an object with properties name and age, as well as a method speak(). In TypeScript, interfaces can be used to describe the shape of objects but cannot implement specific behavior; therefore, methods defined within an interface are abstract.
We can use this interface to define an object that satisfies the requirements of the Person interface:
const person: Person = {
name: 'Alice',
age: 30,
speak() {
console.log(`My name is ${this.name} and I'm ${this.age} years old.`);
}
};
Note that this object must include all properties and methods defined in the interface; otherwise, the TypeScript compiler will report an error.
Interfaces can also be used to define optional and readonly properties. For example:
interface Car {
model: string;
year: number;
color?: string; // Optional property
readonly vin: string; // Readonly property
}
const car: Car = {
model: 'Tesla Model S',
year: 2022,
vin: '1234567890'
};
In this example, the color property is optional and can be omitted. The vin property is readonly and cannot be modified after initialization.