Monday, November 12, 2018

the Promise generic in TypeScript

Stack Overflow has this example of it:

function test(arg: string): Promise<number> {
   return new Promise<number>((resolve, reject) => {
      if (arg === "a") {
         resolve(1);
      } else {
         reject("1");
      }
   });
}

 
 

Here is an example of using their example:

let input = "a";
test(input).then(
   (yin:number) => { console.log(yin + yin) },
   (yang:string) => { console.log(yang) }
);

 
 

The "a" value above is going to trigger the first function in the .then implementation while changing "a" out for a "b" would trip the second function. This has some notes of what is new in TypeScript 3.1 and its first talking point is "Mapped types on tuples and arrays" for which it offers these three lines of code:

type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> };
type Coordinate = [number, number]
type PromiseCoordinate = MapToPromise<Coordinate>;

 
 

The Promise generic appears again! How may we use the three lines of code immediately above? Well, we can have them chase the function from Stack Overflow at the top of this blog posting and then chase all that with this:

let myPromiseCoordinate: PromiseCoordinate = [test("a"), test("b")];
myPromiseCoordinate.forEach((myPromise: Promise<number>) => {
   myPromise.then(
      (yin:number) => { console.log(yin + yin) },
      (yang:string) => { console.log(yang) }
   );
});

No comments:

Post a Comment