← 中文资源

简体中文版本

实例化表达式固定泛型实参

实例化表达式在不调用构造函数的情况下固定泛型实参:派生的类别名继承严格的成员类型,错误的成员类型在编译期就会报错,类型安全无需重复声明。

阅读英文原文

运行结果

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

names: ada, grace
all strings: true
numbers: 2

实现说明

逻辑集中在类 Registry里。 各个操作都建立在顶层绑定之上:StringRegistry、names、NumberRegistry。

使用要点

  • 直接运行文件,输出会带上标签,比如 names:、all strings:、numbers:——输出的每一行都能指回产生它的那次调用。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件用顶层绑定保存自己的状态:StringRegistry、names、NumberRegistry。

核心语句

const names = new StringRegistry().add('ada').add('grace');
const StringRegistry = Registry<string>;
const NumberRegistry = Registry<number>;

代码示例

class Registry<T> {
  items: T[] = [];
  add(item: T): this {
    this.items.push(item);
    return this;
  }
}

// An instantiation expression applies type arguments without calling new
const StringRegistry = Registry<string>;

const names = new StringRegistry().add('ada').add('grace');
console.log('names:', names.items.join(', '));

// StringRegistry.add only accepts strings; add(42) would fail compilation
console.log('all strings:', names.items.every((i) => typeof i === 'string'));

// The same generic class reuses cleanly with a different type argument
const NumberRegistry = Registry<number>;
console.log('numbers:', new NumberRegistry().add(7).add(9).items.length);