T055 Working with Multiple Files and Classes
In this assignment, you’ll practice organizing TypeScript code across multiple files. You’ll create a Person class and a Pet class in separate files, and then bring them together in a main index.ts file.
Setup
- Create three TypeScript files:
person.ts,pet.ts, andindex.ts.
Creating the Pet Class
- In the
pet.tsfile, create a class namedPetwith the following: - A private field named
_nameof typestring. - A constructor that accepts a
nameparameter and initializes the_namefield. - A getter method named
namethat returns the pet’s name.
Creating the Person Class
- In the
person.tsfile, first import thePetclass frompet.ts. - Create a class named
Personwith the following: - A private field named
_nameof typestring. - A private field named
_petof typePet. - A constructor that accepts a
nameparameter and apetparameter, initializing the_nameand_petfields respectively. - A method named
introducethat prints a message in the format: “[Person’s name] has a pet named [Pet’s name].”
Instantiating the Classes
- In the
index.tsfile: - Import both the
PersonandPetclasses. - Create a new instance of the
Petclass named “Whiskers”. - Create a new instance of the
Personclass named “Alice” who owns the pet “Whiskers”. - Call the
introducemethod on thePersoninstance to print the introduction message.
Solution
Solution
pet.ts
export class Pet {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
}
person.ts
import { Pet } from './pet';
export class Person {
private _name: string;
private _pet: Pet;
constructor(name: string, pet: Pet) {
this._name = name;
this._pet = pet;
}
introduce() {
console.log(`${this._name} has a pet named ${this._pet.name}.`);
}
}