Search code examples
typescripttypescript-typingstypescript-genericsreact-typescript

What should the return type of Promise.race be? (Typescript)


For example in the code below, what should the type of response be? Typescript keeps giving me errors such as, Type 'unknown' is not assignable to type 'Promise'

const response: [what type???] = await Promise.race([
      apicall(),
      timeoutPromise(),
    ]);


Solution

  • Typescript cannot be sure which promice will be resolved first or even any of them will be resolved at all. So you should provide a type to Promice.race:

    type PromiseType1 = string
    type PromiseType2 = string
    const apicall = () => new Promise<PromiseType1>(() => {})
    const timeoutPromise = () => new Promise<PromiseType2>(() => {})
    
    const response = await Promise.race<PromiseType1 | PromiseType2>([
      apicall(),
      timeoutPromise(),
    ]);