首页 > 解决方案 > 类型 'R[P]' 不满足约束 '(...args: any) => any'

问题描述

我正在尝试将 reselect 和 redux 与 typescript 集成。我正在导出减速器类型。这是我的类型的样子。

type Reducers = {
    user: Reducer<{
        isLogged: boolean;
        isLogging: boolean;
        isFinished: boolean;
        response: {
            idToken: string;
            sessionState: string;
            accessToken: string;
            refreshToken: string;
            tokenType: string;
            scope: string;
            profile: {
                ...;

我想把它转换成这样的东西

State = {
    user: {
        isLogged: boolean;
        isLogging: boolean;
        isFinished: boolean;
        response: {
            idToken: string;
            sessionState: string;
            accessToken: string;
            refreshToken: string;
            tokenType: string;
            scope: string;
            profile: {
                ...;

这就是我如何成功地做到这一点,但我得到打字稿错误。我相信这是因为 ReturnType 应该与箭头函数一起使用,ReturnType<() => R[P]>但这并没有给我想要的结果

export type CreateState<R> = {
  [P in keyof R]: ReturnType<R[P]>
}
type State = CreateState<Reducers>

打字稿错误信息图片

标签: typescriptreduxreselect

解决方案


您可以使其更通用而无需任何额外的类型:

export type CreateState<R> = {
    [P in keyof R]: R[P] extends (...args: any) => any ? ReturnType<R[P]> : never
}

推荐阅读