Abstract Constructor Types Type Registries

Type a plugin registry with abstract new constructors, then cast to a concrete signature only at the instantiation boundary.

TypescriptConfig Management

Code

typescriptsnippet
40 lines
abstract class TextJob {
  abstract name: string;
  abstract run(input: string): string;
}

class UpperJob extends TextJob {
  name = 'upper';
  run(input: string): string {
    return input.toUpperCase();
  }
}

class ReverseJob extends TextJob {
  name = 'reverse';
  run(input: string): string {
    return [...input].reverse().join('');
  }
}

// Abstract constructor registry: store classes that cannot be instantiated directly
type AbstractCtor<T> = abstract new () => T;

const registry: Record<string, AbstractCtor<TextJob>> = {
  upper: UpperJob,
  reverse: ReverseJob,
};

function create(name: string): TextJob {
  const Ctor = registry[name];
  if (!Ctor) {
    throw new Error('unknown plugin: ' + name);
  }
  // 只在实例化边界把抽象签名收窄为具体构造签名
  const Concrete = Ctor as new () => TextJob;
  return new Concrete();
}

for (const name of Object.keys(registry)) {
  console.log(name, '->', create(name).run('release'));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

upper -> RELEASE
reverse -> esaeler

How the snippet works

Abstract Constructor Types Type Registries reduces to the classes TextJob, UpperJob and ReverseJob and the function create.

Repetition is confined to for (const name of Object.keys(registry)) — the rest of the file is straight-line. The failure path is explicit — Error is raised when the guard condition holds.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • The guard !Ctor short-circuits the flow with an early throw when its condition holds.

Applying it

The entry-point signature is function create(name: string)

Statements that matter

type AbstractCtor<T> = abstract new () => T;
throw new Error('unknown plugin: ' + name);
const Concrete = Ctor as new () => TextJob;

Interactive Tools for This Topic

FAQ

Does `create` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
How does the code behave when input is bad?
The code throws `Error` — the guard `!Ctor` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `create` at load time.