class Person {
constructor(private firstName: string, private lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
describe(): string {
return `This is ${this.firstName} ${this.lastName}.`;
}
}
Code language: TypeScript (typescript)
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceInMeters: number = 0) { console.log(`${this.name} moved ${distanceInMeters}m.`); }}
class Snake extends Animal { constructor(name: string) { super(name); } move(distanceInMeters = 5) { console.log("Slithering..."); super.move(distanceInMeters); }}
class Horse extends Animal { constructor(name: string) { super(name); } move(distanceInMeters = 45) { console.log("Galloping..."); super.move(distanceInMeters); }}
let sam = new Snake("Sammy the Python");let tom: Animal = new Horse("Tommy the Palomino");
sam.move();tom.move(34);Try
class Employee extends Person {
constructor(
firstName: string,
lastName: string,
private jobTitle: string) {
// call the constructor of the Person class:
super(firstName, lastName);
}
}
Code language: TypeScript (typescript)
class Employee extends Person {
//..
}
Code language: TypeScript (typescript)
class Animal { private name: string; constructor(theName: string) { this.name = theName; }}
class Rhino extends Animal { constructor() { super("Rhino"); }}
class Employee { private name: string; constructor(theName: string) { this.name = theName; }}
let animal = new Animal("Goat");let rhino = new Rhino();let employee = new Employee("Bob");
animal = rhino;animal = employee;Type 'Employee' is not assignable to type 'Animal'.
Types have separate declarations of a private property 'name'.2322Type 'Employee' is not assignable to type 'Animal'.
Types have separate declarations of a private property 'name'.Try