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

[Typescript] Builder pattern - 03

时间:2023-02-14 14:36:40浏览次数:41  
标签:map Typescript return get pattern Builder set expect key

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');
});

 

标签:map,Typescript,return,get,pattern,Builder,set,expect,key
From: https://www.cnblogs.com/Answer1215/p/17119468.html

相关文章