实现说明
逻辑集中在类 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);