Is there a specific way to correctly type the following function in TypeScript?
Assuming we have a function
createMap()
that requires:
- a prefix (e.g.
foo
)- and a tuple of suffixes (e.g. ['a', 'b', 'c'])
If we call
, we expect to get the mapped type below:createMap('foo', ['a', 'b', 'c'])
{ a: 'foo.a', b: 'foo.b', c: 'foo.c', }
The actual function logic is pretty straightforward, but defining the return type may not be as easy:
const createMap = <P extends string, S extends string[]>(prefix: P, suffixes: [...S]) => {
return suffixes.reduce((map, suffix) => ({
...map,
[suffix]: `${prefix}.${suffix}`,
}), {});
}
I am aware that this is incorrect, but one might assume it should look something like { [K in S]:
${P}.${K in S} }
.