In TypeScript, an interface is a way to define the structure of an object. It specifies the properties and methods that an object should have. Interfaces are used for type checking during development and for documentation purposes.
Example 1:
index.ts:
interface Person {
name: string;
age: number;
greet: () => void;
}
interface Employee extends Person {
salary: number;
department: string;
welcome(): void;
}
class Manager implements Employee {
salary: number;
department: string;
name: string;
age: number;
constructor(name: string, age: number, salary: number,
department: string) {
this.salary = salary;
this.department = department;
this.name = name;
this.age = age;
}
greet() {
console.log("Greetings: You came to the new world.");
}
welcome() {
console.log("Welcome to the new Job.");
}
}
let manager1 = new Manager('Shyam', 25, 29000, 'Sales & Marketing');
manager1.greet();
manager1.welcome();In TypeScript, you can create an interface and provide an anonymous implementation directly inline. This is useful when you need to define a structure that is used only once and doesn't require a separate named implementation. Here's an example:
Example 2:
index.ts:
interface Person {
name: string;
age: number;
greet: () => void;
}
const person: Person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
},
};
person.greet(); // Output: Hello, my name is John and I'm 30 years old.