Antfish
Antfish

Reputation: 1493

How to create Union or Pick type from an interface in TypeScript?

I have a type for my Redux store object something along the lines of:

 interface StoreState {
    state1: State1Type;
    state2: State2Type;
    state3: {
      state3a: State3aType;
    };
  }

I'd like to create a new type based on StoreState that'd let me pick from any of the types in StoreState as if were a union: NewType: State1Type | State2Type | State3aType

From what I've read it looks like the answer might be in using mapped types, but I can't work out how to implement this.

Upvotes: 1

Views: 229

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

You can extract values' types recursively:

interface StoreState {
    state1: '1';
    state2: '2';
    state3: {
        state3a: '3';
    };
}

type ValuesDeep<T, V = T[keyof T]> = V extends object ? ValuesDeep<V> : V

type NewType = ValuesDeep<StoreState>; // "1" | "2" | "3"

Playground

Upvotes: 2

Related Questions