Sobes.tech
Senior

Is it reliable to trust TypeScript types at runtime? How to ensure backend data validation?

sobes.tech AI

Answer from AI

TypeScript types cannot be fully trusted at runtime because they only exist at compile time and do not affect code execution. After compilation to JavaScript, types are absent.

To ensure validation of data received from the backend, runtime validation must be used. For this, the following are applied:

  • Schema validation libraries, such as zod, io-ts, yup. They allow describing the data structure and checking it at runtime.
  • Explicit checking of fields and types manually.

Example with zod:

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

type User = z.infer<typeof UserSchema>;

async function fetchUser(): Promise<User | null> {
  const response = await fetch('/api/user');
  const data = await response.json();
  const result = UserSchema.safeParse(data);
  if (!result.success) {
    console.error('Invalid data', result.error);
    return null;
  }
  return result.data;
}

Thus, TypeScript helps during development, and runtime validation guarantees data correctness during execution.

Is it reliable to trust TypeScript types at runtime… - sobes.tech