How can you assign types to objects? For example, a user object that looks like this -
const user = {
firstName: "harkirat",
lastName: "singh",
email: "email@gmail.com".
age: 21,
}
To assign a type to the user object, you can use interfaces
interface User {
firstName: string;
lastName: string;
email: string;
age: number;
}
Assignment #1 - Create a function isLegal that returns true or false if a user is above 18. It takes a user as an input.
Assignment #2 - Create a React component that takes todos as an input and renders them
💡Select typescript when initialising the react project using
npm create vite@latest
Interfaces have another special property. You can implement interfaces as a class.
Let’s say you have an personinterface -
interface Person {
name: string;
age: number;
greet(phrase: string): void;
}
You can create a class which implements this interface.
class Employee implements Person {
name: string;
age: number;
constructor(n: string, a: number) {
this.name = n;
this.age = a;
}
greet(phrase: string) {
console.log(`${phrase} ${this.name}`);
}
}
This is useful since now you can create multiple variants of a person (Manager, CEO …)
interfaces to aggregate data