Construct Signatures Type Class Factories
Model a class factory with a construct signature, accept only compatible constructors, and build parsers with different separators.
Code
// 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.