示例工程 06-generics

06-generics/05-generic-class/src/main.ts

typescript · 0.7 KB

运行:06 · generic-class

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:泛型类的类型参数在实例间共享,实例方法可以链式返回 this
export class Stack<T> {
  #items: T[] = [];
 
  push(item: T): this {
    this.#items.push(item);
    return this;
  }
 
  pop(): T | undefined {
    return this.#items.pop();
  }
 
  get size(): number {
    return this.#items.length;
  }
 
  toArray(): readonly T[] {
    return [...this.#items];
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const stack = new Stack<number>();
  stack.push(1).push(2).push(3);
  const popped = stack.pop();
  const lines = [
    String(popped),
    String(stack.size),
    stack.toArray().join(','),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}