ThisCalculator

Everyday

TypeScript JEV API Responses: Safe Handling

Updated · Standard formula, shown below

The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.

TypeScript can handle JEV (JSON Event Viewer) API responses safely by defining precise types that match the response structure and using runtime validation to guard against unexpected data. This article explains how to combine TypeScript’s static typing with runtime checks so your code never assumes a field exists when it might not.

Formula

The calculator above is a simple tool to check whether an HTTP status code falls in the success range (200–299) and to convert response time from milliseconds to seconds. The first output, Valid response, uses the formula if(s>=200 && s<300, 1, 0), where s is the status code. It returns 1 if the response is valid (success) and 0 otherwise. The second output, Parsed events, is t / 1000, converting the response time t (in ms) to seconds. This is a quick sanity check for API response health, not a substitute for full type validation.

Worked Example

Using the default values: status code s = 200 and response time t = 250 ms.

  1. Check validity: if(200>=200 && 200<300, 1, 0) → if(true, 1, 0) → 1 (valid).
  2. Convert time: 250 / 1000 → 0.25 seconds.

The calculator shows a valid response (1) and a parsed time of 0.25 seconds. This matches the formula output.

Background: What Is a JEV API?

JEV, or JSON Event Viewer, is a common pattern in web applications where a server sends a stream of JSON objects representing events (e.g., user actions, system logs, telemetry). The API might return a single JSON object with an array of events, or it might use a streaming format like newline-delimited JSON (NDJSON). The key challenge is that the shape of the data can vary: fields may be missing, null, or of unexpected types, especially when the API evolves or when errors occur.

TypeScript's static type system helps at compile time, but it does nothing at runtime. If the API sends a field that TypeScript thinks is a string but is actually a number, your code will crash or produce incorrect results. That's why you need runtime validation.

How TypeScript's Type System Helps

TypeScript lets you define an interface that describes the expected shape of the API response. For example:

interface JevEvent {
  id: string;
  type: 'click' | 'scroll' | 'purchase';
  timestamp: number;
  data?: Record<string, unknown>;
}

interface JevResponse {
  events: JevEvent[];
  total: number;
  nextCursor?: string;
}

This gives you autocompletion and compile-time checks. If you try to access response.events[0].typ, TypeScript will flag it. However, this only works if the data actually matches the interface. At runtime, the API could return events: null or total: "100" (a string instead of a number). TypeScript won't catch that.

Runtime Validation Libraries

To handle runtime safety, you need a validation library that checks the actual data against a schema. Popular choices include Zod, Yup, and io-ts. Zod is the most widely used in the TypeScript community because it integrates seamlessly with type inference.

Example with Zod:

import { z } from 'zod';

const JevEventSchema = z.object({
  id: z.string(),
  type: z.enum(['click', 'scroll', 'purchase']),
  timestamp: z.number(),
  data: z.record(z.string(), z.unknown()).optional(),
});

const JevResponseSchema = z.object({
  events: z.array(JevEventSchema),
  total: z.number(),
  nextCursor: z.string().optional(),
});

// Use it in your fetch handler
const response = await fetch('/api/events');
const json = await response.json();
const parsed = JevResponseSchema.parse(json); // throws if invalid
// parsed is now typed as { events: JevEvent[], total: number, nextCursor?: string }

If the API returns something unexpected, parse throws an error with a detailed message. You can catch it and handle it gracefully. Zod also has safeParse which returns a result object instead of throwing.

Common Problems and Misconceptions

One common mistake is thinking that TypeScript's as cast is enough. For example, const data = json as JevResponse does not validate anything; it just tells the compiler to trust you. If the data is malformed, you'll get runtime errors that are hard to debug.

Another misconception is that you need to validate every field. In practice, you should validate the fields your code actually uses. For a large event stream, validating everything might be overkill. You can use Zod's .partial() or .pick() to validate only the parts you need.

Also, be aware of the difference between unknown and any. When you parse JSON, the result is any, which disables type checking. You should immediately validate it to a known type, and avoid using any in your codebase.

How to Choose a Validation Strategy

Your choice depends on your project's needs:

  • Small, internal APIs: If you control the API and it's unlikely to change, a simple interface plus a few manual checks might suffice.
  • Third-party or evolving APIs: Use a schema library like Zod to validate and transform data. This also gives you nice error messages.
  • Performance-critical paths: Schema validation adds overhead. You can validate once at the boundary and then use the typed result throughout your app.

For streaming NDJSON, you'll need to parse each line separately. Zod can validate each line, but you'll also need to handle partial lines and errors.

Best Practices for Safe Handling

Here are concrete steps to follow:

  1. Define a schema for the response using Zod or a similar library.
  2. Use safeParse to avoid exceptions in production; log the error and return a fallback.
  3. Validate at the API boundary – right after you get the JSON, before any business logic.
  4. Use TypeScript's unknown for the raw JSON and then narrow it with validation.
  5. Handle null and undefined explicitly in your schema (e.g., .nullable() or .optional()).
  6. Write unit tests that feed malformed data to your validation to ensure it fails gracefully.

Remember that TypeScript is a compile-time tool, and validation is a runtime tool. You need both for full safety.

Frequently Asked Questions

Is TypeScript's type system enough for API safety?

No. TypeScript types are erased at runtime, so they provide no protection against malformed data. You need runtime validation to ensure the data matches what your code expects.

What is the difference between Zod and io-ts?

Both are schema validation libraries. Zod is more popular, has a simpler API, and integrates with TypeScript's inference. io-ts is more functional and has a steeper learning curve but is also powerful.

How do I handle optional fields in a JEV response?

Use Zod's .optional() or .nullable() to indicate that a field may be absent or null. Then your code must check for undefined before using it.

Can I use TypeScript's as to cast JSON to a type?

You can, but it's unsafe. The as cast is a compile-time assertion that doesn't check the actual data. If the data is wrong, you'll get runtime errors. Prefer validation.

What if the API returns a huge stream of events?

For streaming, validate each event individually as it arrives. Use a parser that can handle partial lines, and use a schema that is lightweight. Avoid building a giant array of all events in memory if the stream is infinite.

Related

Formula used
in t | Response time (ms) | ms | 250 | 0
in s | Status code | - | 200 | 0
out pace | Valid response | - | if(s>=200 && s

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.