我正在用类型脚本编写一个函数,它将接受一个请求类型的参数,然后返回一个 struct 为变量的对象.我写的函数是这样的:
export async function getFormData<T>(req: Request): Promise<T> {
let data = {} as T
const formdata = await req.formData();
formdata.forEach((value, key) => {
data[key] = value; // <- This line gives the error
});
return data;
}
我的推理是,当我运行函数getFormData时,我会像这样运行它
const res = await getFormData<myInterface>(req);
个
这样,Res就会有合适的myInterface
类型.但Typescript 总是给我错误
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'.
No index signature with a parameter of type 'string' was found on type 'unknown'
Tl;dr:如何编写一个函数,该函数将返回在我调用函数时指定的类型的对象
这个(Generic Object type in typescript)问题在某种程度上解决了问题,但我得到的所有东西都是‘any’类型