打字稿,redux:如何从尖括号中获取文字?

时间:2018-07-21 13:38:17

标签: typescript redux

假设我们有

type reducerType = Reducer<{user: string;}>
type reducedType = ???  // How to write this?

使得动态结果等于:

type reducedType = {user: string;}

如果有帮助,我们还可以访问实际的 reducer 实例(类型为 reducerType )。

1 个答案:

答案 0 :(得分:0)

Reducer只是一个获取和返回状态的函数,状态是其通用参数。因此,我们可以简单地使用TypeScript 2.8中的选项:

type reducedType = ReturnType<reducerType>;

另一种方法(更复杂,但也更通用)是不仅使用类型,而且使用具有中间(未使用)常量值的辅助函数:

function getReducerType<T>(reducer: Reducer<T>): T {
     // for linters not to argue; we can return anything, in fact, we need only the declaration
    return {} as any;
};
const reducedValue = getReducerType(reducer);
type reducedType = typeof reducedValue;