0

Is there a way in typescript to express the typings of a function that takes in a list of strings, and creates 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' }

Here's what I've tried, without luck:

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)
// Typings for x get resolved to: 
{
  a: "a" | "b";
  b: "a" | "b";
}

1 Answer 1

2

You are really close. You need to specify that the value is same type as key and not the whole set "a"|"b" which is U.

TS Playground Link

const createActionTypes = <T extends readonly string[], U extends T[number]>(
  types: T
): { [key in U]: key } => {
  return types.reduce((typesMap, type) => {
    typesMap[type] = type
    return typesMap
  }, {} as any)
}

const x = createActionTypes(['a', 'b'] as const)

Also, just for clarity, I would avoid using reserved words like type as a variable or function parameter. It required me to look twice to ensure type is not type, but a value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.