All quizzesHard
Advanced OOP Patterns — Series 2
Preview — 3 of 10 questions
javascript
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
return class extends Base {
timestamp = Date.now();
};
}
class User { constructor(public name: string) {} }
const TimestampedUser = Timestamped(User);
const u = new TimestampedUser('Ana');
console.log(u.name, u.timestamp);ACompiles fine — Timestamped is a mixin function: it takes any class constructor and returns a new anonymous class extending it, adding a timestamp property; u has both name (inherited from User) and timestamp (added by the mixin)
BCompile-time error — a mixin function returning a class expression that extends a generic type parameter isn't supported
CCompiles fine, but u.timestamp is undefined at runtime
DCompiles fine, but u.name is inaccessible, since a mixin replaces the base class entirely rather than extending it
javascript
function LogParam(target: object, propertyKey: string, parameterIndex: number) {
console.log(`Parameter ${parameterIndex} of ${propertyKey} is decorated`);
}
class Greeter {
greet(@LogParam name: string): string {
return `Hello, ${name}`;
}
}ACompile-time error — decorators can only be applied to classes and methods, never to individual parameters
BCompiles fine, and LogParam automatically validates that name is a non-empty string every time greet is called
CCompiles fine — a parameter decorator receives the target object, the containing method's name, and the parameter's index within that method's signature; this is commonly used by frameworks (e.g. for dependency injection or validation metadata) to record information about a specific parameter, though the decorator function itself doesn't automatically change the parameter's runtime behavior
DRuntime error — parameter decorators require experimentalDecorators to be enabled, and always throw an error even when it is
javascript
class Config {
static readonly settings: Record<string, string>;
static {
const raw = '{"env":"production"}';
Config.settings = JSON.parse(raw);
}
}
console.log(Config.settings.env);ACompile-time error — static {} blocks are not valid TypeScript/JavaScript syntax
BCompiles fine, but the block runs every time Config.settings is accessed, not just once
CCompiles fine, but Config.settings remains undefined, since a static {} block can't assign to a readonly static property
DCompiles fine — a static {} block runs exactly once, when the class is first evaluated, allowing more complex static-property initialization logic (parsing, computation, even try/catch) than a simple field initializer expression could express; Config.settings.env correctly logs 'production'
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.