zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Builder pattern - 03

typescript 03 pattern Builder
2023-09-14 08:59:11 时间
import { expect, it } from 'vitest';

class TypeSafeStringMap<TMap extends Record<string, string> = {}> {
  private map: TMap;
  constructor() {
    this.map = {} as TMap;
  }

  get<T extends keyof TMap>(key: T): TMap[T] {
    return this.map[key];
  }

  set<K extends string, V extends string>(
    key: K,
    value: V
  ): TypeSafeStringMap<TMap & Record<K, V>> {
    (this.map[key] as any) = value;

    return this as any;
  }
}

const map = new TypeSafeStringMap()
  .set('matt', 'pocock')
  .set('jools', 'holland')
  .set('brandi', 'carlile');

it('Should not allow getting values which do not exist', () => {
  map.get(
    // @ts-expect-error
    'jim'
  );
});

it('Should return values from keys which do exist', () => {
  expect(map.get('matt')).toBe('pocock');
  expect(map.get('jools')).toBe('holland');
  expect(map.get('brandi')).toBe('carlile');
});