0

I have a promise all with a mixed array and I'm using a spread operator to split the output in 2 variables, the first as IUnpackedFile and the rest as IDescriptionBody[]. The way I solved it is casting the 2 variables using the as keyword. Code below:

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

Why can't I type casting the output using a tuple?

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

This is the error I'm getting:

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)[]'.

EDIT: so far I've found this: Proposal: Variadic Kinds Basically it is a proposal that has been in discussion since 30 Oct 2015.

Luca Marangon
  • 762
  • 1
  • 8
  • 13

1 Answers1

0

Why can't I type casting the output using a tuple?

Because you cannot cast an array to a tuple. Here is the same code shown below:

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

More

You are actually not type casting. Just assigning, which is giving you the error same as the example I showed. A type assertion would actually fix it:

declare const foo: number[];
const bar: [number, number] = foo as [number, number]; // OK
basarat
  • 261,912
  • 58
  • 460
  • 511
  • So it is basically what I am already doing: const description = (rest as IDescriptionBody[]) const meshMaterials = (bufferArray as IUnpackedFile) – Luca Marangon May 03 '18 at 05:51