0
0
Typescriptprogramming~10 mins

Why typed classes matter in Typescript - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a typed class property.

Typescript
class Person {
  name: [1];
  constructor(name: string) {
    this.name = name;
  }
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using number or boolean for a name property.
Using any which loses type safety.
2fill in blank
medium

Complete the code to add a typed method that returns the person's name.

Typescript
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }

  getName(): [1] {
    return this.name;
  }
}
Drag options to blanks, or click blank then click option'
Anumber
Bvoid
Cstring
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using void as return type when the method returns a value.
Using number or boolean which do not match the returned value.
3fill in blank
hard

Fix the error in the class by typing the age property correctly.

Typescript
class Person {
  name: string;
  age: [1];
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
Drag options to blanks, or click blank then click option'
Aany
Bboolean
Cstring
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Typing age as string or boolean.
Using any which removes type safety.
4fill in blank
hard

Fill both blanks to create a typed method that sets the person's age.

Typescript
class Person {
  age: number;
  setAge([1]: [2]) {
    this.age = age;
  }
}
Drag options to blanks, or click blank then click option'
Aage
Bstring
Cnumber
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than age.
Typing the parameter as string instead of number.
5fill in blank
hard

Fill all three blanks to create a typed class with a constructor and a method that returns a greeting.

Typescript
class Person {
  name: [1];
  constructor(name: [2]) {
    this.name = name;
  }
  greet(): [3] {
    return `Hello, ${this.name}!`;
  }
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using number or boolean types for name or return type.
Mismatching types between property and constructor parameter.