All quizzesHard
Advanced OOP Patterns
Preview — 3 of 10 questions
What does this type represent?
javascript
type Constructor<T = {}> = new (...args: any[]) => T;
function getInstance<T>(Ctor: Constructor<T>): T {
return new Ctor();
}AA type alias for any function
BA generic interface for factories
CA type that represents a class constructor — something you can call with new to produce a T
DA type that only matches abstract classes
What does InstanceType extract?
javascript
class Database {
connect(url: string): void {}
query(sql: string): Promise<unknown[]> { return Promise.resolve([]); }
}
type DB = InstanceType<typeof Database>;
// DB is: ?Atypeof Database — the class constructor type
B{ connect: Function; query: Function } — a plain object type
CDatabase — the instance type (same as just writing Database)
DConstructor<Database>
What does a class decorator do?
javascript
function Singleton<T extends Constructor>(Base: T): T {
let instance: InstanceType<T>;
return class extends Base {
constructor(...args: any[]) {
if (instance) return instance;
super(...args);
instance = this as unknown as InstanceType<T>;
}
} as T;
}
@Singleton
class AppConfig {
theme = 'dark';
}
const c1 = new AppConfig();
const c2 = new AppConfig();
// c1 === c2?Atrue — @Singleton wraps the class so all new AppConfig() calls return the same instance
Bfalse — @Singleton has no effect on class instantiation
CCompile error — decorators cannot modify constructors
Dfalse — c1 and c2 are always different objects
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.