我正在使用 redux-promise-middleware 和 redux-thunk 来链接我的 promise :
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
});
}
}
上面的代码有效,但在编译时也会产生警告:
TS2339: Property 'then' does not exist on type '{ type: string; payload: Promise<{}>; }'
听起来我需要包括 Promise<...>
某处作为一种类型,所以 typescript 知道 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...
});
似乎相关,但我可以在其中指定操作类型,即 MY_ACTION
?
最佳答案
如你所见in this ts playground变量 a
公开与 Dispatch<any>
类型相同的键, 如您所见,如果将鼠标悬停在错误上,错误消息与您的情况相同。为了访问 promise (以及 then
函数),您将必须访问 payload
调度对象。
this.dispatcher({ ... }).payload.then(....);
编辑1:
如果我们看一下 typings for redux我们可以很快找到 Dispatcher 接口(interface)。
export interface Dispatch<S> {
<A extends Action>(action: A): A;
}
export interface Action {
type: any;
}
然后通过一些重写和一些伪代码的自由使用,我们可以推断出 Dispatch 的类型是一个函数,它接受一个参数,它是一个对象,并返回一个与参数相同类型的对象。
type Dispatch: (action: {type: any, ...}) => {type: any, ...}
输入对象和输出对象的类型都是:
interface {
type: any,
[key: string]: value
}
总而言之,要么 1) 您没有使用 redux 的官方类型,2) redux 的官方类型是错误的,或者 3) 您在实际环境中遗漏了一些东西,实际上代码不起作用。
编辑2:
我还没有尝试过这段代码,所以我不知道它是否真的能解决您的问题。但是您可以尝试重新定义 Dispatch 接口(interface)。
declare module 'redux' {
export interface Action {
type: any;
}
export interface Dispatch<S> {
<A extends Action>(action: A): Promise<S>;
}
}
如您在 this playground 中所见,它是有效的 typescript ,但我以前不必自己这样做,所以这可能无法开箱即用。
如果这不起作用,您可以尝试定义一个与模块同名的命名空间。
namespace redux {
export interface Action {
type: any;
}
export interface Dispatch<S> {
<A extends Action>(action: A): Promise<S>;
}
}
我之前还没有尝试过,所以我不能保证它会起作用。
关于javascript - Typescript 错误 "Property ' then' does not exist"when chaining promises with promise-middleware + thunk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063439/