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.
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:
You can use my fork directly:
npm uninstall p-waterfall
npm install https://github.com/sindresorhus/p-waterfall/tarball/c6802cc6c55f00803a3262db2f119c69d07241ec
You can pass the transformers
array directly, without creating an intermediary variable. This way p-waterfall will get it right. See on StackBlitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With