ts怎么动态生成类型?
求助如何动态生成type ModuleName 和 type Service;然后让我在index.tsx中能方便的查看service的类型
user.ts:
import request from '../request';import { sha256 } from 'js-sha256';
import { Payload } from '@/service/request';
/**
* 用户相关接口请求
*/
const user = {
// 登录
login(param: Payload): Promise<any> {
param.loginPwd = sha256(param.loginPwd);
return request('/agri/pcweb/user/login', param, 'POST');
}
};
export default user;
index.ts:
import { Payload } from '@/service/request';const files = require.context('./module', false, /\.ts$/);
type ModuleName = 'user';
type Service = Record<ModuleName, {}>;
const service = <Service>{};
// type ModuleName = keyof typeof service;
files.keys().forEach((key: string) => {
const fileName = key.replace(/(\.\/|\.ts)/g, '') as ModuleName;
service[fileName] = files(key).default;
});
export default service;
index.tsx:
import service from '@/service';import { Payload } from '@/service/request';
const LoginPage = () => {
interface Values extends Payload {
loginName: string;
loginPwd: string;
};
const onLogin = async (values: Values) =>
values._isMsg = false;
values._loading = false;
const resp = await service.user.login(values);
};
}
以上是 ts怎么动态生成类型? 的全部内容, 来源链接: utcz.com/p/936718.html