Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "p-waterfall" TypeScript Types

I am using p-waterfall and I would like to know how to use the TypeScript types provided. Here are the types.

declare namespace pWaterfall {
  type Task<ValueType, ReturnType> = (
    previousValue: ValueType
  ) => ReturnType | PromiseLike<ReturnType>;

  type InitialTask<ReturnType> = () => ReturnType | PromiseLike<ReturnType>;
}

declare const pWaterfall: {
    <ReturnType>(tasks: [pWaterfall.InitialTask<ReturnType>]): Promise<ReturnType>;
  <ValueType1, ReturnType>(
    tasks: [
      pWaterfall.InitialTask<ValueType1>,
      pWaterfall.Task<ValueType1, ReturnType>
    ]
  ): Promise<ReturnType>;
  <ValueType1, ValueType2, ReturnType>(
    tasks: [
      pWaterfall.InitialTask<ValueType1>,
      pWaterfall.Task<ValueType1, ValueType2>,
      pWaterfall.Task<ValueType2, ReturnType>
    ]
  ): Promise<ReturnType>;
  ...

I put an example (code below) together that if typed would really help me understand how to get the types working with p-waterfall.

import pWaterfall from "p-waterfall";

interface User {
  name: string;
}

const getItemsRequest = async (sliceCount: number): Promise<User[]> => {
  return [{ name: "a" }, { name: "b" }, { name: "c" }].slice(0, sliceCount);
};

const getNames = (results: User[]): string[] => {
  return results.map(item => item.name);
};

const countArrayLength = <T extends unknown[]>(results: T): number => {
  return results.length;
};

(async () => {
  const transformers = [getItemsRequest, getNames, countArrayLength];

  const shouldBeTypeNumberButIsUnknown = await pWaterfall(transformers, 2);

  console.log(`results`, shouldBeTypeNumberButIsUnknown); // 2
})();

shouldBeTypeNumberButIsUnknown is unknown but should be number because the last function passed into pWaterfall returns a number.

like image 239
codeBelt Avatar asked Nov 06 '22 04:11

codeBelt


1 Answers

I've opened a PR for p-waterfall that will allow you to easily do what you want. See here.

In the meantime, there are two workarounds you can use:

  1. You can use my fork directly:

    • npm uninstall p-waterfall
    • npm install https://github.com/sindresorhus/p-waterfall/tarball/c6802cc6c55f00803a3262db2f119c69d07241ec
      • This command installs directly from my commit c6802cc6c55f00803a3262db2f119c69d07241ec
    • And then use the const assertion I explained in the GitHub issue
  2. You can pass the transformers array directly, without creating an intermediary variable. This way p-waterfall will get it right. See on StackBlitz

like image 117
Pedro A Avatar answered Nov 14 '22 21:11

Pedro A