Type checking the API response in typescript

Viewed 6688

I'm curious what happens when you expect a certain type as a response from fetch / Axios / etc and its response is of a different type. Can i detect that mismatch?

interface HttpResponse<T> extends Response {
  parsedBody?: T;
}
export async function http<T>( request: RequestInfo ): Promise<HttpResponse<T>> {
  const response: HttpResponse<T> = await fetch( request );
  response.parsedBody = await response.json();
  return response;
}

// example consuming code
const response = await http<number>(
  "https://thisURLdoesNotReturnANumber"
);

Will the code throw an error? Will it pass silently? How do i detect a mismatch?

2 Answers

Your typescript code traspiles to javascript before browsers execute it. It will look something like this:

export async function http( request ) {
  const response = await fetch( request );
  response.parsedBody = await response.json();
  return response;
}
const response = await http("https://thisURLdoesNotReturnANumber");

No types, as you can see. Browsers know nothing about types defined in typescript.

Later on you may or may not get a runtime error. To throw as early as possible you need to implement a runtime check by youself inside you http<T>() function.
Or you can use a third-party library to do the job. There are plenty of them out there.

Your Typescript code will be parsed to Javascript, so at runtime, when the different type arrives from your api, the type-check is not available anymore.

You won't get any errors.

TypeScript is just a very good help at developing, but sadly, it won't fail on runtime type validations.

Related