Step-by-step guide on leveraging TypeScript types called "p-waterfall"

Utilizing p-waterfall has led me to seek guidance on how to implement the TypeScript types it offers. You can find the relevant types here.

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

An example has been created (see code below) which, when typed properly, will enhance my understanding of utilizing the provided TypeScript types 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 currently labeled as unknown although it should ideally be of type number, given that the last function passed into pWaterfall returns a number.

Answer №1

I have submitted a PR for p-waterfall that enables you to easily achieve your desired outcome. Take a look here.

For now, there are two ways you can address this:

  1. You have the option to utilize my fork directly:

    • npm uninstall p-waterfall
    • npm install https://github.com/sindresorhus/p-waterfall/tarball/c6802cc6c55f00803a3262db2f119c69d07241ec
    • Then proceed with the const assertion as detailed in the GitHub issue
  2. You can directly pass the transformers array without creating an extra variable. This will ensure p-waterfall handles it correctly. View it on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform the property of type any/unknown into a specific generic type T within the map

Suppose I start with... type TypeNonGeneric = { prop1: any, prop2: string }; How do I transform it into... type TypeGeneric<T> = { prop1: T, prop2: string }; I have reviewed the documentation and it appears that I need to create a new generic type ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

I'm having trouble getting forkJoin to trigger

As I create a guard in Angular, I am faced with the challenge of making two distinct HTTP requests and then deciding whether to continue based on both responses. After some research, I learned that forkJoin is the recommended approach for this task, but fo ...

Exploring VSCode Debugger with Typescript: Traversing through Step Over/Into leads to JavaScript file路径

Just starting out with VSCode and using it to debug node.js code written in Typescript. One thing that's been bothering me is that when I stop at a breakpoint and try to "Step Over" or "Step Into", the debugger takes me to the compiled Javascript file ...

Using TypeScript in React, how can I implement automation to increment a number column in a datatable?

My goal is to achieve a simple task: displaying the row numbers on a column of a Primereact DataTable component. The issue is that the only apparent way to do this involves adding a data field with indexes, which can get disorganized when sorting is appli ...

Leveraging the power of NestJS in conjunction with Apollo Server version 2

I recently delved into learning nestjs and decided to give this graphql example a try. The issue I encountered is that the example was originally designed for apollo-server version 1, and I'm having difficulty adapting it to work with apollo-server v ...

Struggling to bring in { useActionState } from 'react' while trying to follow the latest next.js tutorial with next.js v15.0.0-canary.28, react v19.0.0-rc, and types/react v18.2.21

Currently, I am following the tutorial on next.js available at https://nextjs.org/learn/dashboard-app I have reached chapter 14, which focuses on enhancing accessibility, located at https://nextjs.org/learn/dashboard-app/improving-accessibility During on ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

Is it possible to modify a single value in a React useState holding an object while assigning a new value to the others?

In my current state, I have the following setup: const [clickColumn, setClickColumn] = useState({ name: 0, tasks: 0, partner: 0, riskFactor: 0, legalForm: 0, foundationYear: 0 }) Consider this scenario where I only want to update ...

What is the reason behind the slight difference between TypeScript's IterableIterator<> and Generator<> generics?

In TypeScript version 3.6.3, there is a notable similarity between Generator<> and IterableIterator<>. However, when Generator<> extends Iterator<>, the third generic argument (TNext) defaults to unknown. On the other hand, Iterator ...

How can I conceal the word "null" within an Angular 2 input field?

Whenever there is a null value in the JSON, it ends up displaying in the input field. How do I go about hiding it so that only the name shows up instead? <div> <input type="hidden" name="roleUserHidden-{{roleIndex}}" #role ...

Having trouble getting access to FormArray content for validation due to receiving null or undefined errors

CSS Tricks <form [formGroup]="newMovieForm"> <ng-container formArrayName="actors"> <ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index"> <div [formGroupN ...

Steps for confirming whether each element in the array includes the specified search string using Typescript and protractor

How can I verify if each element in an array contains a specific search string in Typescript/Protractor? The issue I faced was that the console statements were returning false because they searched for exact matches instead of the search string. Any sugg ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Every time I attempt to utilize `glidejs`, I encounter the error message stating that "default is not a constructor."

Here is the code snippet I am working with: import Glide from "@glidejs/glide"; const SectionSlider = () => { const UNIQUE_CLASS = "random_string" let MY_GLIDEJS = useMemo(() => { return new Glide(`.${UNIQUE_CLASS}`, { ...

Enter the previous script type

Uncertain about the type to assign here. "HowitterObject" in setHowitters represents data and "...prev' is the ongoing accumulation of data from howitterObject. interface IhowitterMessage { message: string; createAt: number; id: ...

Steps for generating a signal that postpones the primary signal and promptly resets

I am looking to create a signal that will automatically switch to an underlying signal or memo after a specific delay, and reset immediately if the primary signal is cleared. The code snippet below illustrates my desired functionality. import { render } fr ...

What exactly is the meaning of `react-text`?

Can you explain the functionality of react-text? Although it is not present in the code, it shows up in the HTML after rendering. https://i.sstatic.net/s650q.png ...

Production environment experiencing issues with Custom Dashboard functionality for AdminJS

I have successfully integrated AdminJS into my Koa nodejs server and it works perfectly in my local environment. My objective is to override the Dashboard component, which I was able to do without any issues when not running in production mode. However, wh ...

Just starting out with Angular and struggling to understand how to fix the TS(2322) error

Main Code: export class TodosComponent implements OnInit{ todos!: Todo[]; localItem: string; constructor(){ const data = localStorage.getItem("todos"); this.localItem = data; if(this.localItem == null){ this.todos = []; } ...