使用承诺中间件 + thunk 链接承诺时,打字稿错误“属性‘then’不存在”

Fuz*_*ree 5 javascript typescript redux redux-thunk redux-promise-middleware

我正在使用 redux-promise-middleware 和 redux-thunk 来链接我的承诺:

import { Dispatch } from 'redux';

class Actions {
    private static _dispatcher: Dispatch<any>;
    public static get dispatcher(): Dispatch<any> {
        return Actions._dispatcher;
    }
    public static test() {
        this.dispatcher({
            type: 'MY_ACTION',
            payload: new Promise(resolve => resolve('hi'));
        }).then(result => {
            console.log(result); // this works
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码有效,但在编译时也会生成警告:

TS2339:类型“{ type: string;”上不存在属性“then” 有效载荷:承诺<{}>;}'

听起来我需要将Promise<...>某处作为类型包含在内,以便打字稿知道这then实际上是返回的对象上的属性,dispatcher()但我无法消除错误。

https://github.com/gaearon/redux-thunk/issues/103

import { Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';
import { getStore, IState } from './my_store';

let store = getStore();

// Create myThunkAction function with a type of ThunkAction<R, S, E>
let myThunkAction: ThunkAction<Promise<string>, IState, null> =
    (dispatch: Dispatch<IState>, getState: () => IState) => {
        return new Promise<string>((resolve, reject) => {

            // do async stuff with getState() and dispatch(), then...
            resolve('done!');

        });
    }

store.dispatch(myThunkAction)
.then(() => {
    // do stuff after the thunk has finished...
});
Run Code Online (Sandbox Code Playgroud)

似乎相关,但我可以在哪里指定操作类型,即MY_ACTION

Oli*_*n04 4

正如您在这个 ts 游乐场中看到的,变量a公开了与 类型相同的键Dispatch<any>,并且如果您将鼠标悬停在错误上,您可以看到,错误消息与您的情况相同。为了访问 Promise(以及函数then),您必须访问payloadDispatch 对象的 。

this.dispatcher({ ... }).payload.then(....);
Run Code Online (Sandbox Code Playgroud)

编辑1:

如果我们看一下redux 的类型,我们可以很快找到 Dispatcher 接口。

export interface Dispatch<S> {
    <A extends Action>(action: A): A;
}
export interface Action {
  type: any;
} 
Run Code Online (Sandbox Code Playgroud)

然后通过一些重写和伪代码的一些自由使用,我们可以推断出 Dispatch 的类型是一个函数,它接受一个对象的参数,并返回一个与参数相同类型的对象。

type Dispatch: (action: {type: any, ...}) => {type: any, ...}
Run Code Online (Sandbox Code Playgroud)

输入对象和输出对象都是以下类型:

interface {
    type: any,
    [key: string]: value
}
Run Code Online (Sandbox Code Playgroud)

总之,要么 1) 您没有使用 redux 的官方类型,2) redux 的官方类型是错误的,或者 3) 您在实际环境中错过了一些东西,而实际上代码不起作用。

编辑2:

我还没有尝试过这段代码,所以我不知道它是否能真正解决你的问题。但您可以尝试重新定义 Dispatch 接口。

declare module 'redux' {
    export interface Action {
       type: any;
    }
    export interface Dispatch<S> {
        <A extends Action>(action: A): Promise<S>;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您在这个 Playground中看到的那样,它是有效的打字稿,但我以前不需要自己这样做,所以这可能无法开箱即用。

如果这不起作用,您可以尝试定义与模块同名的命名空间。

namespace redux {
    export interface Action {
       type: any;
    }
    export interface Dispatch<S> {
        <A extends Action>(action: A): Promise<S>;
    }
}
Run Code Online (Sandbox Code Playgroud)

不过我之前还没有尝试过,所以我不能保证它会起作用。