I'm learning TypeScript and for the purposes of learning I try to rewrite the code written in JavaScript What will be the best way to use functions within several classes. I would like every class to have access to the function sayHello()
I'm trying to rewrite my JavaScript code into TypeScript
JavaScript:
class Guest {
firstName;
lastName;
constructor() {
}
static sayHello() {
console.log(`Hi, my name is ${this.firstName}${this.lastName}`);
}
}
class Employee {
firstName;
lastName;
permissionLevel;
static sayHello() {
console.log(`Hi, my name is ${ this.firstName }${ this.lastName }`);
}
}
class Director {
firstName;
lastName;
constructor() {
}
static sayHello() {
console.log(`Hi, my name is ${this.firstName}${this.lastName}`);
}
}
let clerk = new Employee();
var director = new Director("John", "Smith");
Director.sayHello();
TypeScript
function sayHello(firstName: string, lastName: string): void {
console.log(`Hi, my name is ${firstName}${lastName}`)
}
class Guest {
firstName: string;
lastName: string;
constructor() {
}
}
class Employee {
firstName: string;
lastName: string;
permissionLevel: string;
}
class Director {
firstName;
lastName;
constructor() {
}
}
const clerk = new Employee();
const director = new Director("John", "Smith");
Director.sayHello();
I would like the sayHello () function to be available in every class.
Additionally, I am wondering whether to create an interface for firstName and lastName to make the code more readable
interface Person {
firstName: string,
lastName: string
}
Could someone recommend me how to best translate this code to TypeScript.
firstNameandlastNameto be undefined in classes?