skip to Main Content

How to extract a new type alias from an object’s value

const test = {
'a': ['music','bbq','shopping'],
'b': ['move','work']
};

How to get it from a test object

type Types = 'music' | 'bbq' | 'shopping' | 'move' | 'work'

2

Answers


  1. const test = {
      'a': ['music','bbq','shopping'] as const,
      'b': ['move','work'] as const
    };
    
    type Types = test.a[number] | test.b[number]
    
    Login or Signup to reply.
  2. You can do this quite easily using as const:

    const test = {
    'a': ['music','bbq','shopping'],
    'b': ['move','work']
    } as const;
    
    type Elements = typeof test[keyof typeof test][number];
    

    The only solution I can think of that is not using as const is defining an interface with the exact elements of the arrays:

    interface Foo {
        a: ['music', 'bbq', 'shopping'],
        b: ['move', 'work']
    };
    
    type Elements2 = Foo[keyof Foo][number];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search