0
0
Typescriptprogramming~5 mins

Parameter properties shorthand in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the parameter properties shorthand in TypeScript?
It is a way to declare and initialize class properties directly in the constructor parameters by adding an access modifier (like <code>public</code>, <code>private</code>, or <code>protected</code>) before the parameter name.
Click to reveal answer
beginner
How does parameter properties shorthand help when writing classes?
It reduces the amount of code by combining property declaration and assignment into one step inside the constructor, making the code shorter and easier to read.
Click to reveal answer
beginner
Rewrite this class using parameter properties shorthand:<br><pre>class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}</pre>
<pre>class Person {
  constructor(public name: string) {}
}</pre>
Click to reveal answer
intermediate
Which access modifiers can be used with parameter properties shorthand?
You can use public, private, protected, and readonly modifiers to control visibility and mutability of the property.
Click to reveal answer
beginner
True or False: Parameter properties shorthand can only be used with public parameters.
False. Parameter properties shorthand can be used with public, private, protected, and readonly parameters.
Click to reveal answer
What does the parameter properties shorthand do in TypeScript?
ADeclares and initializes class properties directly in constructor parameters
BCreates global variables automatically
CDefines functions inside constructor parameters
DRemoves the need for constructors
Which of these is a valid use of parameter properties shorthand?
Aconstructor(private age: number) {}
Bconstructor(age: number) { this.age = age; }
Cconstructor(age) { this.age = age; }
Dconstructor(public age) { age = 10; }
What happens if you omit the access modifier in a constructor parameter?
AThe parameter becomes a class property
BThe parameter is just a normal parameter, no property is created
CThe code will not compile
DThe parameter becomes a global variable
Can you use readonly with parameter properties shorthand?
AOnly with <code>public</code> modifier
BNo, <code>readonly</code> is not allowed
COnly with <code>private</code> modifier
DYes, to make the property immutable
Which of these is NOT a benefit of parameter properties shorthand?
ALess code to write
BCombines declaration and assignment
CAutomatically creates getter and setter methods
DImproves readability
Explain how parameter properties shorthand works and why it is useful.
Think about how you normally declare properties and assign them in the constructor.
You got /4 concepts.
    Write a simple TypeScript class using parameter properties shorthand with at least two properties.
    Use public or private before the parameter names in the constructor.
    You got /3 concepts.