ConstructorParameters And InstanceType Derive Class Types
ConstructorParameters and InstanceType recover constructor tuples and instance types from class definitions, so factories stay typed without repeated shapes.
Code
// Derive types from a class definition: ConstructorParameters yields the ctor arg tuple,
// InstanceType yields the instance type - factories and registries never hand-write them twice
interface JobOptions {
name: string;
intervalMs: number;
}
class PollJob {
options: JobOptions;
constructor(options: JobOptions) {
this.options = options;
}
start(): void {
console.log(`poll ${this.options.name} every ${this.options.intervalMs}ms`);
}
}
class CleanupJob {
paths: string[];
constructor(paths: string[]) {
this.paths = paths;
}
start(): void {
console.log('cleanup paths:', this.paths.join(','));
}
}
// ConstructorParameters reconstructs the arg tuple: calling the factory needs no redeclared shape
type PollArgs = ConstructorParameters<typeof PollJob>;
const args: PollArgs = [{ name: 'feed', intervalMs: 5000 }];
// InstanceType reconstructs the instance type: mixed instances in a container still safely expose common methods
type AnyJob = InstanceType<typeof PollJob> | InstanceType<typeof CleanupJob>;
const jobs: AnyJob[] = [new PollJob(...args), new CleanupJob(['tmp/a', 'tmp/b'])];
for (const job of jobs) job.start();
type ExpectEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
? true
: never;
const locked: ExpectEqual<PollArgs, [JobOptions]> = true;
console.log('poll args locked:', locked);Output
Captured from a sandboxed run of this snippet in the build pipeline.
poll feed every 5000ms
cleanup paths: tmp/a,tmp/b
poll args locked: trueInside the snippet
Count the classes PollJob and CleanupJob as the entire surface area of ConstructorParameters And InstanceType Derive Class Types.
Iteration happens inside for (const job of jobs) job.start(); — everything outside it runs once.
Putting it to use
Output lines are prefixed (poll $, cleanup paths:, poll args locked:), making each step’s effect easy to spot.
Core lines
type ExpectEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
? true
: never;
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring.
Report a problem with this exampleOpens a pre-filled issue on GitHub.