JSFiddle - React, Tailwind, and code Playground
by mswilson4040
TypeScript
// Class with an interface
interface IPerson {
firstName: string;
lastName: string;
age: number;
getFullName(): string;
}
class Person implements IPerson {
public firstName: string;
public lastName: string;
public age: number;
constructor(firstName: string, lastName: string, age: number) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
getFullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
const person: IPerson = new Person('John', 'Doe', 44);
console.log(person);
console.log(person.getFullName());
// Passing around an interface (injection would work the sameish)
class Task {
public person: IPerson;
public taskName: string;
constructor(person: IPerson, taskName: string) {
this.person = person;
this.taskName = taskName;
console.log(this); // Note that person is was passed in as an interface, but it's still got all it's class methods
}
}
const task = new Task(person, 'Task 1');
// Interface Only
const personInterface: IPerson = <IPerson>{
firstName: 'John',
lastName: 'Doe',
age: 44
};
console.log(personInterface);
console.log(personInterface.getFullName()); // Error: getFullName is not a function