typescript 类型为“unknown”的参数不能赋值给类型为“{}”的参数

egdjgwm8  于 2023-02-13  发布在  TypeScript
关注(0)|答案(2)|浏览(583)

下面是我的代码

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'的参数不能赋值给类型'{}'的参数。

abithluo

abithluo1#

这里的问题是,你需要帮助TypeScript理解你所处理的对象的类型,fetch API无法提前知道返回对象的形状,所以你必须定义它并Assert结果符合它。
看看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将被称为类型ResObj,你可以开始操作它了。一个问题是Object.values()Array.prototype.flat()的标准库的类型并不反映你对它们所做的事情。我们可以为它们构建一些自定义类型......但是在本例中,我将用类型匹配的新函数 Package 它们:

// 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)
  );

并且没有错误,编译器理解ResArrClothing对象的数组。
链接到代码
好吧,希望能有所帮助;祝你好运!

inn6fuwd

inn6fuwd2#

问题

Res.json()返回any类型的值,当Object.values接收any类型的输入时,它返回unknown[]。当strictNullChecks打开时,TypeScript不允许我们将unknown类型的值赋给{}类型的参数。
这一解释也附在评论中。

const func = async () => {

    const Res = await fetch(`https://foo0022.firebaseio.com/.json`);

    /**
     * The ResObj is that `Res.json()` returns is of type `any`.
     */
    const ResObj = await Res.json();

    if (!Res.ok || !ResObj) {
        throw new Error("Page Not Found 404");
    }

    /**
     * When we pass Object.values a type of `any`, 
     * it produces an array of type `unknown[]`.
     */
    const unknownArray = Object.values(ResObj);

    /**
     * `Object.values` has two signatures: 
     * 
     * * `values(o: {}): any[];`
     * * `values<T>(o: { [s: string]: T } |  ArrayLike<T>): T[];`
     * 
    * When `strictNullCheck` is `true`, we cannot assign `unknown` to `{}`.
    */
    const ResArr = unknownArray.map(unknownItem => Object.values(unknownItem));
};

两种可能的解决方案

1.禁用strictNullChecks(不推荐)。
1.将类型添加到ResObj
后一个选项如下所示:

type MyKnownType = {
    prop1: string;
    prop2: number;
    prop3: boolean;
};

const ResObj: MyKnownType = await Res.json();

相关问题