Exercise Solutions: TypeScript

Part 1 - Declare Variables With Type

  1. Declare the variables with type based on the information given in the table.

    1let spacecraftName: string = 'Determination';
    2let speedMph: number = 17500;
    3let kilomitersToMars: number = 225000000;
    4let kilometersToTheMoon: number = 384400;
    5let milesPerKilometer: number = 0.621;
    

Part 2 - Print Days to Mars

  1. Use a template literal to print variables.

    console.log(`${spacecraftName} would take ${daysToMars} days to get to Mars.`);
    

Part 3 - Create a Function

  1. In the space indicated, define a function that calculates the days it would take to travel to a location.

    1function getDaysToLocation(kilometersAway: number): number {
    2   let milesAway: number = kilometersAway * milesPerKilometer;
    3   let hours: number = milesAway / speedMph;
    4   return hours / 24;
    5}
    

Part 4 - Create a Spacecraft Class

Create a Spacecraft class.

 1class Spacecraft {
 2   milesPerKilometer: number = 0.621;
 3   name: string;
 4   speedMph: number;
 5
 6   constructor(name: string, speedMph: number) {
 7      this.name = name;
 8      this.speedMph = speedMph;
 9   }
10
11   getDaysToLocation(kilometersAway: number): number {
12      let milesAway: number = kilometersAway * this.milesPerKilometer;
13      let hoursToMars: number = milesAway / this.speedMph;
14      return hoursToMars / 24;
15   }
16}

Part 5 - Export and Import the SpaceLocation Class

After following the steps in Part 5, your Spacecraft class should look slightly different:

 1class Spacecraft {
 2   milesPerKilometer: number = 0.621;
 3   name: string;
 4   speedMph: number;
 5
 6   constructor(name: string, speedMph: number) {
 7      this.name = name;
 8      this.speedMph = speedMph;
 9   }
10
11   getDaysToLocation(kilometersAway: number): number {
12      let milesAway: number = kilometersAway * this.milesPerKilometer;
13      let hours: number = milesAway / this.speedMph;
14      return hours / 24;
15   }
16
17   printDaysToLocation(location: SpaceLocation) {
18      console.log(`${this.name} would take ${this.getDaysToLocation(location.kilometersAway)} days to get to ${location.name}.`);
19   }
20}