Monday, 16 November 2020

Typescript: Generate Type from Object keys and Array string values

I'm looking to generate a type from an Object's keys, and values of arrays of strings. The type needs to represent all the possible strings, i.e.

const Actions = {
  foo: ['bar', 'baz'],
}

# type generated from Actions to equal:
type ActionsType = 'foo' | 'bar' | 'baz'

I need to retain Actions as it's to be passed to a method, therefore:

const Actions = {
  foo: ['bar', 'baz'],
} as const


type ActionsType = keyof typeof Actions | typeof Actions[keyof typeof Actions][number]

whilst generating the type correctly didn't allow me to pass Actions to a method expecting Record<string, string[]> as the keys and values became readonly.

How can I generate the required type whilst still being able to use Actions as a non-readonly Object?



from Typescript: Generate Type from Object keys and Array string values

No comments:

Post a Comment