Can anyone tell me why should I use Interface in Typescript and what are they?
Example with Interface:
interface Person {
firstName: string;
lastName: string;
}
class Student {
fullName: string;
constructor(public firstName: string, public lastName: string) {
this.fullName = firstName + " " + lastName;
}
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let student = new Student("John", "Smith");
console.log(greeter(student));
OUTPUT: Hello, John Smith
Example without Interface same output:
class Student {
fullName: string;
constructor(firstName: string, lastName: string) {
this.fullName = firstName + " " + lastName;
}
}
function greeter(person : Student) {
return "Hello, " + person.fullName;
}
let student = new Student("John", "Smith");
console.log(greeter(student));
OUTPUT: Hello, John Smith
Why is interface useful in this particular case? I find it hard to understand use of interface in typescript. Any detailed explanation is very appreciated!