0
0
Typescriptprogramming~5 mins

Class property declarations in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a class property declaration in TypeScript?
A class property declaration defines a variable inside a class to hold data for each object created from that class. It sets the name and type of the property.
Click to reveal answer
beginner
How do you declare a public property named name of type string in a TypeScript class?
You write: <pre>class Person {
  public name: string;
}</pre> This means every Person object has a <code>name</code> property that holds a string.
Click to reveal answer
intermediate
What is the difference between declaring a property with and without an access modifier in TypeScript?
If you declare a property without an access modifier, it is public by default. Using private or protected changes who can access the property.
Click to reveal answer
beginner
Can you assign a default value to a class property in its declaration? Show an example.
Yes. You can assign a default value like this:<pre>class Car {
  color: string = "red";
}</pre> Every new Car object will have <code>color</code> set to "red" unless changed.
Click to reveal answer
intermediate
What happens if you declare a property but do not initialize it in the class or constructor?
The property exists but is undefined until you assign a value. TypeScript may warn if you don't initialize or mark it optional.
Click to reveal answer
Which keyword declares a property that can only be accessed inside the class?
Aprivate
Bpublic
Cprotected
Dreadonly
What is the default access level of a class property if no modifier is specified?
Aprivate
Bprotected
Cpublic
Dreadonly
How do you assign a default value to a class property in TypeScript?
AUsing an equals sign in the property declaration
BInside the constructor only
CUsing a method
DYou cannot assign default values
Which of these is a valid property declaration in TypeScript?
Aconst age: number;
Blet age: number;
Cvar age: number;
Dage: number;
What does the readonly modifier do when used with a class property?
AMakes the property private
BPrevents the property from being changed after initialization
CAllows the property to be changed anywhere
DMakes the property optional
Explain how to declare and initialize a class property with a default value in TypeScript.
Think about using an equals sign in the property line.
You got /3 concepts.
    Describe the difference between public, private, and protected class properties in TypeScript.
    Consider who can see or change the property.
    You got /3 concepts.