Is there a way in TypeScript to define the types for a function that takes a list of strings and returns an object where each key's value is the key itself?
const createActionTypes = (types: string[]) => {
return types.reduce((typesMap, type) => {
typesMap[type] = type
return typesMap
}, {})
}
// Input
createActionTypes(['a', 'b'])
// Output
{ a: 'a', b: 'b' }
I've attempted the following approach but without success:
const createActionTypes = <T extends readonly string[], U extends T[number]>(
types: T
): { [key in U]: U } => {
return types.reduce((typesMap, type) => {
typesMap[type] = type
return typesMap
}, {})
}
const x = createActionTypes(['a', 'b'] as const)
// The typings for x resolve to:
{
a: "a" | "b";
b: "a" | "b";
}