这是我的代码
const Res = await fetch(`https://foo0022.firebaseio.com/.json`);
const ResObj = await Res.json();
if (!Res.ok || !ResObj) {
throw new Error("Page Not Found 404");
}
const ResArr = await Object.values(ResObj)
.map(v => Object.values(v).flat())//error
.flat()
.filter(({ title }) => title.includes(Search))
在该行中,我得到这个错误“ .map(v => Object.values(v).flat())”,我得到了这个错误类型'unknown'的参数不能分配给类型'{}'的参数。该问题如何解决?
这里的问题是您需要帮助TypeScript了解您要处理的对象的类型。该fetch
API无法事先知道返回的对象的形状将是,所以你必须定义,并断言他结果符合它。
查看https://foo0022.firebaseio.com/.json的内容,我建议类似以下内容:
interface ResObj {
Mens: {
Hat: Clothing[];
Jacket: Clothing[];
Pants: Clothing[];
Shoes: Clothing[];
Suit: Clothing[];
};
New: Clothing[];
}
interface Clothing {
agility: boolean[];
alt: string;
color: string[][];
id: string;
location?: string; // fix this
Location?: string; // fix this
material: string;
price: string[][];
prodState: string;
saiz: string[][];
shipping: string;
sold: string;
src: string[][];
title: string;
to: string;
}
但是,当然,这是否正确取决于某种API文档。假设是正确的,您可以走得更远:
const Res = await fetch(`https://foo0022.firebaseio.com/.json`);
const ResObj: ResObj | undefined = await Res.json();
if (!Res.ok || !ResObj) {
throw new Error("Page Not Found 404");
}
现在ResObj
将称为type ResObj
,您可以开始对其进行操作。一个问题是标准库的类型Object.values()
,Array.prototype.flat()
而不反映您对它们的操作。我们可以为它们构建一些自定义类型...但是在这种情况下,我将使用类型匹配的新函数包装它们:
// return an array of all object values...
// if the object is already an array, the output is the same type.
// otherwise it's the union of all the known property types
function vals<T extends object>(
arr: T
): Array<T extends Array<infer U> ? U : T[keyof T]> {
return Object.values(arr); // need es2017 lib for this
}
// Flatten an array by one level...
function flat<T>(
arr: Array<T>
): Array<Extract<T, any[]>[number] | Exclude<T, any[]>> {
return arr.flat(); // need esnext lib for this
}
如果您以前从未使用过TypeScript,那么这些函数的类型可能会造成混淆,尤其是因为它们依赖于条件类型来挑逗数组属性。
然后我们可以像这样重写您的代码:
const ResArr = flat(vals(ResObj).map(v => flat(vals(v)))).filter(
({ title }) => title.includes(Search)
);
而且没有错误,并且编译器理解这ResArr
是一个Clothing
对象数组。
好吧,希望能有所帮助;祝好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句