← 中文资源

简体中文版本

ConstructorParameters 与 InstanceType 反推类类型

ConstructorParameters 从类定义反推构造参数元组,InstanceType 反推实例类型:工厂与注册表不必手写两遍形状,混合实例容器也能安全调用公共方法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

poll feed every 5000ms
cleanup paths: tmp/a,tmp/b
poll args locked: true

实现说明

逻辑集中在类 PollJob、CleanupJob里。 这个示例中仅有的重复出现在 for (const job of jobs) job.start(); 里。

使用要点

  • 直接运行文件,输出会带上标签,比如 cleanup paths:、poll args locked:——输出的每一行都能指回产生它的那次调用。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。

核心语句

type ExpectEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2
  ? true
  : never;

代码示例

// 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);