TypeScript:如何键入返回函数的返回类型

标签 typescript redux types

仍在尝试学习这种打字系统,不确定是否可行。
我正在使用 redux 和 redux 工具包,并提到在创建 redux 存储后,您可以创建存储的调度和状态的类型化版本。
直接从他们的网站:

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最后一个例子中的常量。

最佳答案

这只是深入研究函数返回类型以获得返回类型成员的类型的问题。
我们可以使用 TypeScript 的 Indexed Types完成此操作如下

type MemberType = MyType[memberKey];
其中我们获得了键为 memberKey 的成员的类型类型 MyType , 其中 memberKey是一个有效的键,例如字符串或数字文字或常量或唯一符号。
在本例中,获取成员类型getStatedispatchcreateStore 返回的对象的当它被调用时,我们会写
// 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();

关于TypeScript:如何键入返回函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66374260/

相关文章:

typescript - Nuxt/ typescript : Cannot access this - TS2339: Property 'XXX' does not exist on type

javascript - 使用 TypeScript 创建 SVG 元素

angular - 如何在angular2中使用谓词

angular - 处理 Ionic 3 应用程序 401 错误的正确工作流程

vba - 寻找返回 Integer 的 WorksheetFunction 方法

javascript - 无法解构 'chats' 的属性 'this.props.data',因为它未定义

javascript - 通过 Redux 和 Redux 路由器处理用户身份验证

javascript - 使用 Lodash 和 React 对数字字符串进行排序?

MySQL:插入 float ,最后是一个整数

types - 如何读取 coq 量词 `forall P: Set -> Prop` ?