【问题标题】:Typescript promise all mixed array and spread operatorTypescript 承诺所有混合数组和扩展运算符
【发布时间】:2018-10-13 06:26:06
【问题描述】:

我有一个使用混合数组的承诺,我使用扩展运算符将输出拆分为 2 个变量,第一个为 IUnpackedFile,其余为 IDescriptionBody[]。 我解决它的方法是使用 as 关键字转换 2 个变量。代码如下:

    return Promise.all<IUnpackedFile | IDescriptionBody>([
      unpackFromHttp("/data/withTexture/5782622127702409215.dat"),
      ...texturePromises
    ])
  .then(([bufferArray, ...rest]) => {
    // casting here
    const description = (rest as IDescriptionBody[]).reduce(
      (res, val) => {
        res[val.CellId] = val;
        return res;
      },
      {} as IDescription
    );

    const meshMaterials = extractMesh(
      // casting here
      (bufferArray as IUnpackedFile).result,
      description
    );

为什么我不能使用元组类型转换输出?

then(([bufferArray, ...rest]: [IUnpackedFile , IDescriptionBody[]])

这是我得到的错误:

Argument of type '([bufferArray, ...rest]: [IUnpackedFile, IDescriptionBody[]]) => void' is not assignable to parameter of type '((value: (IDescriptionBody | IUnpackedFile)[]) => void | PromiseLike<void>) | null | undefined'.
  Type '([bufferArray, ...rest]: [IUnpackedFile, IDescriptionBody[]]) => void' is not assignable to type '(value: (IDescriptionBody | IUnpackedFile)[]) => void | PromiseLike<void>'.
    Types of parameters '__0' and 'value' are incompatible.
      Type '(IDescriptionBody | IUnpackedFile)[]' is not assignable to type '[IUnpackedFile, IDescriptionBody[]]'.
        Property '0' is missing in type '(IDescriptionBody | IUnpackedFile)[]'.

编辑: 到目前为止,我发现了这个:Proposal: Variadic Kinds 基本上这是自 2015 年 10 月 30 日以来一直在讨论的提案。

【问题讨论】:

  • 你使用的是哪个版本的 TypeScript?
  • "打字稿": "^2.8.3",
  • texturePromises有固定数量吗?
  • 很遗憾没有。

标签: typescript promise destructuring spread-syntax


【解决方案1】:

为什么我不能使用元组类型转换输出?

因为您不能将数组强制转换为元组。下面是相同的代码:

declare const foo: number[];
const bar: [number, number] = foo; // Error: property `0` is missing

更多

您实际上不是类型转换。只是分配,这会给您带来与我展示的示例相同的错误。类型断言实际上修复它:

declare const foo: number[];
const bar: [number, number] = foo as [number, number]; // OK

【讨论】:

  • 所以基本上我已经在做: const description = (rest as IDescriptionBody[]) const meshMaterials = (bufferArray as IUnpackedFile)
猜你喜欢
  • 1970-01-01
  • 2022-09-23
  • 2021-09-02
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 2018-04-07
  • 2018-03-31
  • 1970-01-01
相关资源
最近更新 更多