[Typescript] Builder pattern - 03

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

 

posted @   Zhentiw  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-02-14 [Angular 8 Unit Testing] Testing a dump component
2020-02-14 [Functional Programming] Use a Javascript Array to Construct a Maybe
2018-02-14 [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
2018-02-14 [Angular] Provide Feedback to Progress Events with Angular’s HttpRequest Object
2018-02-14 [Angular] Fetch non-JSON data by specifying HttpClient responseType in Angular
2018-02-14 [Angular] Read Custom HTTP Headers Sent by the Server in Angular
2018-02-14 [Angular] Set Metadata in HTTP Headers with Angular HttpHeaders
点击右上角即可分享
微信分享提示