Search code examples
typescripttypestyping

TS define type to equal one of values of typed array


Lets assume I have an access to a type Keys that is defined like so:

type Keys = ('AA' | 'BB' | 'CC')[]
  1. How can I create a new type Key, using type Keys, so that this new type be equal to:
type Key = 'AA' | 'BB' | 'CC'

Note that I cannot literally specify allowed values (AA, BB, etc), I only have Keys type available to work with.


Solution

  • You can use an indexed type query:

    type Keys = ('AA' | 'BB' | 'CC')[]
    type Key = Keys[number]
    

    Playground Link