Construct Signatures Type Class Factories

Model a class factory with a construct signature, accept only compatible constructors, and build parsers with different separators.

TypescriptConfig Management

Code

typescriptsnippet
22 lines
// A construct signature describes classes that new can instantiate.
type ParserCtor = new (separator: string) => {
  parse(input: string): string[];
};

class CsvLineParser {
  constructor(private readonly separator: string) {}

  parse(input: string): string[] {
    return input.split(this.separator).map((part) => part.trim());
  }
}

function buildParser(Ctor: ParserCtor, separator: string): { parse(input: string): string[] } {
  return new Ctor(separator);
}

const comma = buildParser(CsvLineParser, ',');
console.log(comma.parse('alpha, beta, gamma'));

const semicolon = buildParser(CsvLineParser, ';');
console.log(semicolon.parse('one; two; three'));

How the code works

Construct Signatures Type Class Factories reduces to the class CsvLineParser and the function buildParser.

The result is a fresh construction, so callers can keep their originals.

Using it

The main signature reads function buildParser(Ctor: ParserCtor, separator: string)

Key statements

return input.split(this.separator).map((part) => part.trim());
type ParserCtor = new (separator: string) => {
  parse(input: string): string[];
};
return new Ctor(separator);

Interactive Tools for This Topic

FAQ

Does `buildParser` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `buildParser` at load time.