JavaScript / TypeScript · API data

JavaScript and TypeScript API validation interview question

TypeScript can check how your code uses a value, but an API can still send unexpected data. Explain where JavaScript runtime checks are needed before you trust a response.

Published by RoleHello. References are linked in the guide.

Does a TypeScript type assertion validate an API response?

No. Writing value as User tells the TypeScript compiler to treat the value as a User. The assertion is removed when the code becomes JavaScript. It does not inspect the object, convert its fields, or reject a response with missing data.

Treat data from an external source as unknown until your code has checked what it needs. With unknown, the compiler requires you to narrow the type before using its properties. With any, you lose that protection.

This example checks that a parsed JSON value has the string field the application needs:

type User = { name: string };

function parseUser(value: unknown): User {
  if (
    typeof value !== "object" ||
    value === null ||
    !("name" in value) ||
    typeof value.name !== "string"
  ) {
    throw new Error("Expected a user with a string name");
  }

  return { name: value.name };
}

These checks run in JavaScript. TypeScript follows the control flow and knows that value.name is a string after the invalid cases have been rejected. The example uses property narrowing supported in TypeScript 4.9 and later.

The function validates only this small contract. It allows an empty name and ignores additional fields. If the application requires a nonempty name or a particular identifier format, add those checks. For larger responses, a schema validation library can keep runtime checks and inferred types together.

At the API boundary, also handle HTTP failures and invalid JSON. A successful network request does not prove the response matches your application’s model. Decide how validation errors reach the user and avoid displaying or logging an entire response that might contain private data.

In an interview, point to the exact checks that run at runtime. Replacing unknown with a type assertion would remove the compiler’s objection while leaving the incoming data unchecked.

Technical references