首页 > 其他分享 >[Typescript] Builder pattern - 02

[Typescript] Builder pattern - 02

时间:2023-02-13 18:22:32浏览次数:39  
标签:02 const pattern Builder list num unshift push BuilderTuple

export class BuilderTuple<TList extends any[] = []> {
  list: TList;

  constructor() {
    this.list = [] as any;
  }

  push<TNum extends number>(num: TNum): BuilderTuple<[...TList, TNum]> {
    this.list.push(num);

    return this as any;
  }

  unshift<TNum extends number>(num: TNum): BuilderTuple<[TNum, ...TList]> {
    this.list.unshift(num);

    return this as any;
  }
}

const builderBeforePush = new BuilderTuple();
const listBeforePush = builderBeforePush.list;
//     ^? []

const builderAfterPush = builderBeforePush.push(1).push(2).push(3);
//     ^? BuilderTuple<[1, 2, 3]>
const listAfterPush = builderAfterPush.list;
//     ^? [1,2,3]

const builderAfterUnshift = builderBeforePush.unshift(1).unshift(2).unshift(3);
//     ^? BuilderTuple<[3, 2, 1]>
const listAfterUnshift = builderAfterUnshift.list;
//     ^? [3,2,1]

 

标签:02,const,pattern,Builder,list,num,unshift,push,BuilderTuple
From: https://www.cnblogs.com/Answer1215/p/17117309.html

相关文章