All quizzesMedium
Inheritance & Polymorphism — Series 2
Preview — 3 of 10 questions
javascript
class Point {
constructor(public readonly x: number, public readonly y: number) {}
}
const p = new Point(1, 2);
p.x = 10;ACompiles fine — readonly only prevents reassignment from outside the constructor; instance methods can still mutate it freely
BCompile-time error — a readonly parameter property can only be assigned once, during construction; p.x = 10 from outside the class violates that
CRuntime error: "Cannot assign to read only property 'x'"
DThis is invalid syntax — public and readonly can't be combined on a single constructor parameter
javascript
class Account {
#balance = 0;
private pin = "0000";
deposit(amount: number) { this.#balance += amount; }
}
const a = new Account();
console.log(a.pin);
console.log((a as any).pin);ABoth console.log calls compile fine and print "0000"
BBoth calls are compile-time errors, and there is no way to bypass either restriction
Ca.pin is a compile-time error, since pin is private — but (a as any).pin compiles, because as any sidesteps TypeScript's compile-time-only private check; a genuine JS private field like #balance would still be inaccessible even through any, since it's enforced by the JavaScript runtime itself, not just the type checker
D#balance and private pin behave identically in every respect, including at runtime
javascript
class Singleton {
private static instance: Singleton;
protected constructor() {}
static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
const s1 = Singleton.getInstance();
const s2 = new Singleton();ASingleton.getInstance() compiles fine; new Singleton() from outside the class is a compile-time error, because the constructor is protected — only code within the class itself (or a subclass) can invoke it directly
BBoth lines compile fine — protected only restricts property access, not constructors
CBoth lines are compile-time errors — a protected constructor prevents even the class's own static methods from creating instances
Dnew Singleton() compiles fine, but throws a runtime error when called from outside the class
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.