Home > Blockchain >  Conditional type based on whether success or error typescript
Conditional type based on whether success or error typescript

Time:08-25

I'm trying to return both errors and success from a function

type Result = ResultSuccess | ResultFailure;
interface ResultSuccess {
    success: true,
    response: Interface1
}
interface ResultFailure{
    success: failure,
    error: Interface2
}

This works fine, but then in my typescript code

// 'responses' is Result[]
const successfulRequests = responses.filter((x) => x.success).map((x) => x.response)

Here there's a type error because the x.response cannot determine if it's a success or failure (therefore would exist or not), despite checking for the type being 'success: true'

Help is appreciated.

CodePudding user response:

Array.filter does not modify the type of the array without you explicitly asking for it. You can make you filter function into a type guard to narrow the type:

const successfulRequests = responses
  .filter((x): x is ResultSuccess => x.success)
  .map((x) => x.response);

This includes the safety net you want of it not blindly using a wrong type:

const successfulRequests = responses
  .filter((x): x is number => x.success) // Type Error: A type predicate's type must be assignable to its parameter's type. Type 'number' is not assignable to type 'Result'. ts(2677)
  .map((x) => x.response);

CodePudding user response:

responses.filter(x => x.success) returns type Result[] You have to explicitly tell typescript what type you now have i.e. do this:

const successfulRequests = (responses.filter(x => x.success) as ResultSuccess[]).map(x.response)
  • Related