我在我的反应本机(类型记录) redux项目中使用redux-thunk。我使用thunkWithExtraArgument帮助器提供我的阿波罗客户端变量的引用,因为我得到了返回函数的三个参数,即
...
return async (dispatch, getState, client) =>
...
// and with typescript
import { NormalizedCacheObject } from 'apollo-cache-inmemory'
import ApolloClient from 'apollo-client'
import { Dispatch } from 'redux'
import { ReduxStore } from '../interfaces/redux.ts';
...
return async (dispatch: Dispatch, getState: () => ReduxStore, client: ApolloClient<NormalizedCacheObject>): Promise<void>) => {
...
}我已经在任何地方输入了大量的代码,所以有什么解决方案吗?
目前,我所做的是:
import { NormalizedCacheObject } from 'apollo-cache-inmemory'
import ApolloClient from 'apollo-client'
import { Dispatch } from 'redux'
import { ReduxStore } from '../interfaces/redux.ts'
// actually i outsources both GetState and Client types
type GetState = () => ReduxStore
// where ReduxStore is custom defined interface
type Client = ApolloClient<NormalizedCacheObject>
const fetchSomeData = (id: string) => {
return async (dispatch: Dispatch, getState: GetState, client: Client): Promise<void>) => {
...
}
}我试过并需要的是
...
export type Thunk = (dispatch: Dispatch, getState: () => ReduxStore, client: ApolloClient<NormalizedCacheObject>): Promise<void>
...
// action creator
const fethcSomeData = (id: string) => {
return async (dispatch, getState, client): Thunk => {
...
}
}}发布于 2019-08-19 19:23:06
您应该能够使用语境类型为您推断参数类型,方法是让编译器认识到您需要一个Thunk类型的值。由于我没有react/redux类型(问题实际上是关于我认为的一般问题),所以我将使用一些虚构的内容:
type Spronk = (x: string, y: number, z: boolean) => Promise<string>;最安全的方法是注释此类型的变量并返回它:
const fethcSomeData = (id: string) => {
const ret: Spronk = async (x, y, z) => (z ? x : y.toFixed());
return ret;
};或者您可以使用一个类型断言,它更简洁,但更不安全(它将使您缩小值):
const fthecSomeData = (id: string) => {
return <Spronk>(async (x, y, z) => (z ? x : y.toFixed()));
};无论哪种方式都有希望对你有用。祝好运!
更新:这就是我所说的不安全的意思。以下是一个错误:
const errorCaught: Spronk = async (x, y, z) => (z ? x : y); // error!
// (string | number) is not assignable to string我已经注释了errorCaught的类型为Spronk。编译器确认我返回的是string | number而不是string,这意味着errorCaught不是真正的Spronk,而是更广泛的类型。注释一个变量比分配给它的值更窄,这是一个错误。
const errorSuppressed = <Spronk>(async (x, y, z) => (z ? x : y)); // no error在这里,我断言errorCaught的类型是Spronk。编译器仍然会识别值比Spronk更宽,但是类型断言特别允许您说值的类型比编译器能够验证的更窄。有时这种灵活性是有用的,但它是危险的。在errorSuppressed的情况下,我们故意对编译器撒谎,这会在运行时给我们带来麻烦:
errorSuppressed("a", 1, false).then(s => console.log(s.charAt(0))); // compiles, but
// at runtime: "TypeError, s.charAt is not a function"希望这是合理的。
发布于 2019-08-19 19:39:32
作为@jcalz的第二个选项类型断言,最新的类型记录编译器警告说
Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead所以用这种方式是比较好的
const fetchSomeData = (id: string) => {
return <Spronk>(async (x, y, z) => (z ? x : y.toFixed()));
};
to
const fetchSomeData = (id: string) => {
return (async (x, y, z) => (z ? x : y.toFixed())) as Spronk;
};https://stackoverflow.com/questions/57562525
复制相似问题