[Typescript] Understanding Generics at Different Levels of Functions
The following code
import { expect, it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';
export interface Cache<T> {
get: (key: string) => T | undefined;
set: (key: string, value: T) => void;
// You can fix this by only changing the line below!
clone: <U>(transform: (elem: T) => U) => Cache<U>;
}
const createCache = <T>(initialCache?: Record<string, T>): Cache<T> => {
const cache: Record<string, T> = initialCache || {};
return {
get: (key) => cache[key],
set: (key, value) => {
cache[key] = value;
},
clone: (transform) => {
const newCache: Record<string, any> = {};
for (const key in cache) {
newCache[key] = transform(cache[key]);
}
return createCache(newCache);
},
};
};
it('Should let you get and set to/from the cache', () => {
const cache = createCache<number>();
cache.set('a', 1);
cache.set('b', 2);
expect(cache.get('a')).toEqual(1);
expect(cache.get('b')).toEqual(2);
});
it('Should let you clone the cache using a transform function', () => {
const numberCache = createCache<number>();
numberCache.set('a', 1);
numberCache.set('b', 2);
const stringCache = numberCache.clone((elem) => {
return String(elem);
});
const a = stringCache.get('a');
expect(a).toEqual('1');
type tests = [Expect<Equal<typeof a, string | undefined>>];
});
The most important part is to understand how clone
function was typed.
export interface Cache<T> {
get: (key: string) => T | undefined;
set: (key: string, value: T) => void;
clone: <U>(transform: (elem: T) => U) => Cache<U>;
}
So clone
function take an transform
function as input arguement, and the clone
function itself returns a Cache
verson of the inner transform's
return type.
This is the way to do it:
clone: <U>(transform: (elem: T) => U) => Cache<U>;
You CANNOT put U
inside transform function:
clone: (transform: <U>(elem: T) => U) => Cache<U>; // does NOT work, U won't be available to Cache if it is defined in transform function
And good thing about this generic function, U
type will be auto infer from the return type of transform function.
it('Should let you clone the cache using a transform function', () => {
const numberCache = createCache<number>();
numberCache.set('a', 1);
numberCache.set('b', 2);
const stringCache = numberCache.clone((elem) => {
return String(elem);
});
const a = stringCache.get('a');
expect(a).toEqual('1');
type tests = [Expect<Equal<typeof a, string | undefined>>];
});