OOP Architecture — Series 3

Preview — 3 of 10 questions

javascript
type AbstractCtor<T = object> = abstract new (...args: any[]) => T;

function Timestamped<TBase extends AbstractCtor>(Base: TBase) {
  abstract class Timed extends Base {
    createdAt = new Date();
  }
  return Timed;
}

abstract class Entity {
  abstract id(): string;
}

class User extends Timestamped(Entity) {
  id(): string { return "u1"; }
}
ACompile-time error — a class expression may not extend a type parameter
BCompiles fine — the constraint is an abstract construct signature, so abstract bases are accepted, and the factory's return type is inferred
CCompile-time error — the returned class is abstract, so User cannot extend it
DCompiles fine, but new User().createdAt is any, because the mixin's return type cannot be inferred

javascript
interface Ctx { count: number }

function bump(this: Ctx, by: number): number {
  return this.count + by;
}

const ctx: Ctx = { count: 1 };

const a = bump.call(ctx, 2);
const b = bump(2);
ABoth compile — this is always any inside a standalone function
BBoth fail — this may only be typed on class methods
Cb compiles and returns NaN; a is a compile-time error because call erases the this type
Da compiles; b is a compile-time error — the declared this type has no matching receiver at a bare call

javascript
class Box<T> {
  constructor(public value: T) {}
}

class Animal { name = ""; }
class Dog extends Animal { bark() {} }

const a: Box<Animal> = new Box<Dog>(new Dog());

class SBox<in out T> {
  constructor(public value: T) {}
}
const b: SBox<Animal> = new SBox<Dog>(new Dog());
Aa compiles — structural comparison treats the mutable value bivariantly; b fails, because in out declares T invariant and that annotation is enforced
BBoth compile — variance annotations are advisory only
CBoth fail — generic classes are invariant in TypeScript
Da fails and b compiles — the annotation relaxes the default invariance

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.