[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');
});
相关文章
- [Typescript] NoInfer
- [Typescript] Defining exclusive properties with TypeScript
- [Typescript 4.9] TypeScript 4.9: satisfies operator
- [Typescript] Make Typescript Stick
- [Typescript] Making TypeScript Stick - 3
- [Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)
- [VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS
- [Typescript] Map a Discriminated Union to an Object
- [Typescript] 102. Hard - String to Number
- [Typescript] Get a TypeScript package ready for release to NPM
- [Typescript] 52. Medium - ObjectEntries
- [Typescript] Making TypeScript Stick - 6 - infer, build a ConstructorArg Type
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Create Type From Any Given Data in TypeScript
- [TypeScript] Infer the Return Type of a Generic Function Type Parameter
- TypeScript 里的 module 解析过程 - Module Resolution
- TypeScript学习笔记(四)—— TypeScript提高