typescript - 将打字稿类型从函数提取到对象
问题描述
尝试从给定的函数类型生成类型。我想直接从函数中获取返回类型并映射到下面显示的对象的键。我ReturnType
试过了,但它不接受这种reducers
结构。
type A = { a: string }
type B = { b: string }
type Reducers = {
aA: (a) => A,
bB:(b) => B,
}
const reducers: Reducers = {
aA: (a) => { a },
bB: (b) => {b },
}
如何获得商店状态
namespace Store { // I will provide this
type Project = { // here is where I need to generated types based on reducer function like`type Project = ....`
aA: A,
bB: B,
}
}
解决方案
我不确定你想要什么,但这里是如何ReturnType
在映射类型中使用:
type Project = {
[K in keyof Reducers]: ReturnType<Reducers[K]>
}
……或更通用的版本:
interface ReducerDict {
[key: string]: (...args: any[]) => any
}
type Project<T extends ReducerDict> = {
[K in keyof T]: ReturnType<T[K]>
}
推荐阅读
- laravel - Laravel-vue jwt 令牌刷新
- django - 如何正确序列化其模型具有外键且也采用 ImageField 的对象?
- java - 如何获取 ScrollView 的每个 EditText 语音结果
- javascript - HTML Flows Strange(内容出现在错误的位置?)
- bash - 调试分隔和回显学生或学生分数的 .bash 文件时遇到问题
- hazelcast - Hazelcast Entry Processor:当对象影响其他地图中的对象时
- cmake - 未知的 cmake 命令“append_list_if”
- pyspark - 在运行 K 时花费大量时间意味着 Python Spark
- google-bigquery - bigquery 超时限制。需要帮助提高查询效率
- excel - 尝试在起点和终点之间复制/粘贴和转置多个范围