TypeScript:如何为返回的函数类型注明返回类型

4

我还在努力学习这个打字系统,不确定是否可行。

我正在使用redux和redux toolkit,并且提到在创建redux store之后,可以创建一个经过类型定义的存储dispatch和state版本。

直接从他们的网站上:

import { configureStore } from '@reduxjs/toolkit'
// ...

const store = configureStore({
  reducer: {
    one: oneSlice.reducer,
    two: twoSlice.reducer
  }
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

我的问题是我需要延迟存储的配置。

import { configureStore } from '@reduxjs/toolkit'
// ...

const createStore = () => configureStore({
  reducer: {
    one: oneSlice.reducer,
    two: twoSlice.reducer
  }
});

// in some other class ///
const store = createStore();

有没有办法在代码中使用第一种方法中提到的类型?

编辑 我希望能够注释最后一个例子中的store常量。


我不确定我理解了。您是想在最后一个示例中显式注释store的类型,还是想注释createStore的返回类型? - Aluan Haddad
@AluanHaddad 我想在最后一个例子中注释 store 的类型。 - kamcknig
在第二个例子中,将 export type MyStore = ReturnType<typeof createStore>; 添加到导出 createStore 的模块中。然后您可以导入该类型并使用它。我认为这是一种不好的做法。类型推断是您的朋友。 - Aluan Haddad
1
我进行了修改,实际上是这样的 export type AppState = ReturnType<ReturnType<typeof createStore>['getState']>;。你的方式给了我 () => state 的返回类型,而我需要的是 state - kamcknig
1
我几天前回答了一个非常类似的问题https://dev59.com/Ib_qa4cB1Zd3GeqPLJgn#66324900,在那个问题中,他们想要传递初始状态的选项,所以它与@Aluan的答案略有不同,但大体相同。 - Linda Paiste
显示剩余5条评论
1个回答

2

这只是通过深入到函数返回类型来获取返回类型成员类型的问题。

我们可以使用TypeScript的索引类型来实现如下:

type MemberType = MyType[memberKey];

我们要获取类型为MyType的键名为memberKey的成员类型,其中memberKey是一个有效的键名,可以是字符串、数字字面量或常量,或唯一符号。

在这种情况下,为了获取调用createStore时返回对象的getStatedispatch成员的类型,我们需要编写如下代码:

// store.ts

export const createStore = () => configureStore({
  reducer: {
    one: oneSlice.reducer,
    two: twoSlice.reducer
  }
});

// The type of the member `dispatch` of the store returned by `createStore`.
export type StoreDispatch = ReturnType<typeof createStore>["dispatch"];

// The type of the member `getState` of the store returned by `createStore`.
export type StoreGetState = ReturnType<typeof createStore>["getState"];  

请注意,我们可以继续深入挖掘,例如获取这些成员的返回类型,如下所示:
// The return type of the member `getState` of the store returned by `createStore`.
export type AppState = ReturnType<ReturnType<typeof createStore>["getState"]>;

因为语法可能变得笨重,我们可以使用中间类型声明将其分解成更易读的形式

type AppStore = ReturnType<typeof createStore>;

type AppStoreGetState = AppStore["getState"];

export type AppState = ReturnType<AppStoreGetState>;

无论如何,我们现在可以像其他类型一样使用这些类型。
以下是一个人为制造的例子。
// test.ts

import { createStore, AppState } from "./store";

const store = createStore();

const state: AppState = store.getState();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接