typescript

Is it possible to validate types at runtime in Typescript?


Is it possible to validate that an object has attributes defined by an interface at runtime? I'm trying to make an API call from client side and I would to validate that the result is of the type that I'm expecting it to be. Here is an example:

interface IEvent {
  id: string;
  title: string;
}

function get(id: string) {
  const client = new Api({});
  client.get<IEvent>(`/api/events/${id}.json`).then((response: AxiosResponse<IEvent>) => {
    const { data } = response;
    // validate that `data` has attributes in IEvent interface
  });
}

Solution

  • TypeScript types are erased at compile time. In fact, the most popular (actually, as far as I know, the only) implementation of TypeScript simply compiles to ECMAScript, which doesn't have types.

    It would theoretically be possible to compile the types in such a way that they are retained in ECMAScript, but the TypeScript team has specified that types must be erased at compile time. The reason for this is that they want to make it possible for Babel to compile TypeScript as well, and Babel doesn't known anything about TypeScript types; it literally just deletes the type information.