typescript - 如何从 TypeScript 中的接口创建 Union 或 Pick 类型?
问题描述
我的 Redux 存储对象有一个类型,类似于:
interface StoreState {
state1: State1Type;
state2: State2Type;
state3: {
state3a: State3aType;
};
}
我想创建一个基于 StoreState 的新类型,它可以让我从 StoreState 中的任何类型中进行选择,就好像是一个联合:NewType: State1Type | State2Type | State3aType
从我读到的内容看来,答案可能是使用映射类型,但我不知道如何实现这一点。
解决方案
您可以递归地提取值的类型:
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"
推荐阅读
- ios - 当我从 main.m 更改为 appdegelegate.swift 时,React-native IOS 应用程序在启动时变为空白
- php - 使用子值上的动态键对多维数组进行排序 - PHP
- c++ - 如何在 curl 中获取 curl/curl.h?
- java - 从 tika-app 调用 ctakes 解析器时出现异常
- scala - 如何在 O(n) 时间内使用不可变集合同时保留匹配和不匹配的部分
- macos - 在 MacOS 上的另一个屏幕上打开弹出菜单
- c++ - istringstream 和读取浮点数的 C++ 问题
- git - 取消设置/忘记/替换用户 git Credential.Helper 并记住新用户
- javascript - 无法通过 Javascript 从 JSON 中获取值
- java - Java类方法中没有计算公式