Skip to content

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

  1. Create three TypeScript files: person.ts, pet.ts, and index.ts.

Creating the Pet Class

  1. In the pet.ts file, create a class named Pet with the following:
  2. A private field named _name of type string.
  3. A constructor that accepts a name parameter and initializes the _name field.
  4. A getter method named name that returns the pet’s name.

Creating the Person Class

  1. In the person.ts file, first import the Pet class from pet.ts.
  2. Create a class named Person with the following:
  3. A private field named _name of type string.
  4. A private field named _pet of type Pet.
  5. A constructor that accepts a name parameter and a pet parameter, initializing the _name and _pet fields respectively.
  6. A method named introduce that prints a message in the format: “[Person’s name] has a pet named [Pet’s name].”

Instantiating the Classes

  1. In the index.ts file:
  2. Import both the Person and Pet classes.
  3. Create a new instance of the Pet class named “Whiskers”.
  4. Create a new instance of the Person class named “Alice” who owns the pet “Whiskers”.
  5. Call the introduce method on the Person instance 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}.`);
    }
}

index.ts

import { Person } from './person';
import { Pet } from './pet';

let whiskers = new Pet("Whiskers");
let alice = new Person("Alice", whiskers);
alice.introduce();