Class Methods in OOP in TypeScript
Now let's learn how to create class methods. Let's say we have a class User with a property name:
class User {
name: string = '';
}
Let's make a method that returns the user name, specifying the return value type:
class User {
name: string = '';
getName(): string {
return this.name;
}
}
Now let's make a method that changes the value of the name. The name will be passed as a parameter and for this parameter we must also specify the type:
class User {
name: string = '';
getName(): string {
return this.name;
}
setName(name: string): void {
this.name = name;
}
}
Create a class Student with properties name and age. Add methods to get and change these properties.