typescript promise type code example

Example 1: type a promise

/*The generic type of the Promise should correspond to the 
non-error return-type of the function. The error is implicitly 
of type any and is not specified in the Promise generic type. */
function test(arg: string): Promise<number> {
    return new Promise<number>((resolve, reject) => {
        if (arg === "a") {
            resolve(1);
        } else {
            reject("1");
        }
    });
}

Example 2: typescript promise

new Promise<boolean>((res, rej) => {
  res(true);
})
.then(res => {
  console.log(res);
  return false;
})
  .then(res => {
  console.log(res);
  return true;
})
  .then(res => {
  console.log(res);
})
  .catch(error => {
  console.log('ERROR:', error.message);
});

Example 3: typescript get type from promise

function promiseOne() {
  return Promise.resolve(1)
}
    
const promisedOne = promiseOne()
    
// note PromiseLike instead of Promise, this lets it work on any thenable
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T
    
type PromiseOneThenArg = ThenArg<typeof promisedOne> // => number
// or
type PromiseOneThenArg2 = ThenArg<ReturnType<typeof promiseOne>> // => number