首页 > 解决方案 > 如何从 TypeScript 中的接口创建 Union 或 Pick 类型?

问题描述

我的 Redux 存储对象有一个类型,类似于:

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

我想创建一个基于 StoreState 的新类型,它可以让我从 StoreState 中的任何类型中进行选择,就好像是一个联合:NewType: State1Type | State2Type | State3aType

从我读到的内容看来,答案可能是使用映射类型,但我不知道如何实现这一点。

标签: typescript

解决方案


您可以递归地提取值的类型:

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"

操场


推荐阅读