Typescript:如何将导出的默认模块的类型动态推断为Object



我有一个redux存储,看起来像这个

store
--index.ts
--utils.ts
--modules
--user.ts

现在,在我的根存储index.ts中,我在下面配置了一个redux store

import { configureStore } from "@reduxjs/toolkit";
import { updateModules } from "./utils";
const modules = {};
updateModules(modules);
const store = configureStore({
reducer: {
...modules // this is to auto import modules and put it here
// user: user
}
});
export default store;
// Type of store.getState get lost cuz of dynamically adding modules
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

实用程序.ts:

import { camelize } from "utils/string-util";
import { LoseObject } from "./types";
export const updateModules = (modules: LoseObject): void => {
// Allow us to dynamically require all redux module files.
const requireModule = require.context(
// Search for files in the current directory.
"./modules",
// Search for files in subdirectories.
true,
// Include any .ts files that are not types file or a unit test.
/^((?!types|.unit.).)*.ts$/
);
requireModule.keys().forEach((fileName) => {
const moduleName = camelize(fileName.split("/")[1]);
/**
* I want to put the type of exported default type to each of these modules dynamically
*/
modules[moduleName] = requireModule(fileName).default;
});
};

问题:如果我不使用该实用程序并手动添加每个模块以进行存储,它会提供每个模块的状态类型,如IUserState或我提供给状态的任何模块。但如果我动态地这样做,并扩展这些模块中动态创建的object,它就失去了type。我需要帮助来推断每个模块接收到的默认类型,然后将其注册存储。

SandBox链接-https://codesandbox.io/s/wonderful-sara-wscq2?file=/src/App.tsx

这在TypeScript中是不可能的。最好的办法是自动生成代码,但最终会得到一个固定的.ts文件。这是大多数框架解决这个问题的方法。

最新更新