Typescript interface
Created By: chatGPT
In TypeScript, an interface is a powerful way to define the shape of an object. It allows you to specify the properties and their types that an object must adhere to. Interfaces can also define methods, making it easier to ensure that classes adhere to a certain contract.
// Defining a simple interface
interface Person {
name: string;
age: number;
greet: () => void;
}
// Example of using the interface
const user: Person = {
name: 'Alice',
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
user.greet(); // Output: Hello, my name is Alice
You can also extend interfaces, which helps in creating a more complex structure by inheriting properties and methods from other interfaces. This helps maintain a clean and manageable codebase.
// Extending an interface
interface Employee extends Person {
employeeId: number;
work: () => void;
}
// Example of an Employee object
const employee: Employee = {
name: 'Bob',
age: 25,
employeeId: 101,
greet() {
console.log(`Hello, my name is ${this.name}`);
},
work() {
console.log(`I am working as employee #${this.employeeId}`);
}
};
employee.greet(); // Output: Hello, my name is Bob
employee.work(); // Output: I am working as employee #101
Interfaces can also be used with function types. This is particularly useful for defining callbacks or higher-order functions in TypeScript.
// Defining a function type interface
interface StringFormatter {
(input: string): string;
}
// Implementing the function type interface
const toUpperCase: StringFormatter = (input: string) => {
return input.toUpperCase();
};
console.log(toUpperCase('hello')); // Output: HELLO
Interfaces in TypeScript can also describe the properties of indexable types, allowing you to define objects that are indexed by a key.
// Indexable types interface
interface StringArray {
[index: number]: string;
}
const myArray: StringArray = ['Hello', 'World'];
console.log(myArray[0]); // Output: Hello