0
0
Typescriptprogramming~10 mins

Parameter properties shorthand in Typescript - Interactive Code Practice

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

Complete the code to declare a class with a constructor that uses parameter properties shorthand to create a public property.

Typescript
class Person {
  constructor(public [1]: string) {}
}

const p = new Person("Alice");
console.log(p.name);
Drag options to blanks, or click blank then click option'
Aage
Bname
Cvalue
Dtitle
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add public before the parameter.
Using a different parameter name than the property you want.
2fill in blank
medium

Complete the code to create a private property using parameter properties shorthand.

Typescript
class Car {
  constructor(private [1]: number) {}
  getSpeed() {
    return this.speed;
  }
}

const car = new Car(100);
console.log(car.getSpeed());
Drag options to blanks, or click blank then click option'
Aspeed
Bdistance
Ctime
Dpower
Attempts:
3 left
💡 Hint
Common Mistakes
Using a public or protected keyword instead of private.
Choosing a parameter name unrelated to the property.
3fill in blank
hard

Fix the error in the constructor by using parameter properties shorthand correctly.

Typescript
class Book {
  title: string;
  constructor([1]: string) {
    this.title = title;
  }
}

const b = new Book("My Book");
console.log(b.title);
Drag options to blanks, or click blank then click option'
Atitle
Bprivate title
Cpublic title
Dreadonly title
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding any visibility keyword.
Trying to assign the parameter without declaring the property.
4fill in blank
hard

Fill both blanks to create a readonly property using parameter properties shorthand and access it in a method.

Typescript
class User {
  constructor([1] [2]: string) {}
  getUsername() {
    return this.username;
  }
}

const user = new User("john_doe");
console.log(user.getUsername());
Drag options to blanks, or click blank then click option'
Areadonly
Busername
Cpublic
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using private instead of readonly.
Using a different property name than the one accessed.
5fill in blank
hard

Fill all three blanks to create a protected property with parameter properties shorthand, initialize it, and access it in a subclass.

Typescript
class Animal {
  constructor([1] [2]: string) {}
}

class Dog extends Animal {
  getType() {
    return this.[3];
  }
}

const dog = new Dog("mammal");
console.log(dog.getType());
Drag options to blanks, or click blank then click option'
Aprotected
Btype
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using private which blocks subclass access.
Using different names for the property in constructor and method.