0
0
Typescriptprogramming~5 mins

Access modifiers public private protected in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the public access modifier mean in TypeScript?
The public modifier means the property or method can be accessed from anywhere: inside the class, subclasses, and outside the class.
Click to reveal answer
beginner
What is the effect of the private access modifier in TypeScript?
The <strong>private</strong> modifier restricts access to the property or method only within the class where it is declared. It cannot be accessed from outside or subclasses.
Click to reveal answer
beginner
How does the protected access modifier work in TypeScript?
The <strong>protected</strong> modifier allows access to the property or method inside the class and its subclasses, but not from outside these classes.
Click to reveal answer
intermediate
Consider this TypeScript code snippet:<br><pre>class Animal {
  protected name: string;
  constructor(name: string) {
    this.name = name;
  }
}
class Dog extends Animal {
  public bark() {
    console.log(`${this.name} barks`);
  }
}</pre><br>Why can <code>this.name</code> be accessed inside <code>bark()</code>?
Because <code>name</code> is <strong>protected</strong>, it can be accessed inside the subclass <code>Dog</code>. Protected members are accessible in the class and its subclasses.
Click to reveal answer
intermediate
What happens if you try to access a <strong>private</strong> property from a subclass in TypeScript?
You get a compile-time error because <strong>private</strong> properties are only accessible within the class they are declared in, not in subclasses.
Click to reveal answer
Which access modifier allows a property to be accessed anywhere, including outside the class?
Aprotected
Bprivate
Cpublic
Dreadonly
If a property is marked as private, where can it be accessed?
AOnly inside the class it is declared
BInside the class and subclasses
CAnywhere in the program
DOnly outside the class
Which access modifier allows access in the class and its subclasses but not outside?
Aprivate
Bprotected
Cpublic
Dstatic
What will happen if you try to access a protected property from outside the class hierarchy?
AIt will work fine
BIt will be undefined
CRuntime error
DCompile-time error
Which of these is NOT an access modifier in TypeScript?
Aexternal
Bprivate
Cpublic
Dprotected
Explain the differences between public, private, and protected access modifiers in TypeScript.
Think about who can see or use the property or method.
You got /3 concepts.
    Describe a real-life example where you might use each access modifier in a TypeScript class.
    Imagine a company with public services, private offices, and protected areas for managers.
    You got /3 concepts.