Skip to content

Blind Spots of Handling Untyped Data

If you’re a type-fanatic and you’re extremely cautious and overzealous about the type safety of your code, then you probably bought all in on TypeScript. That is great but how do you handle data which is untyped because the source is unknown or the data is dynamic?

Untyped JSON Data

A prime example of this is when you have to perform a JSON.parse() operation on a string of input and this is a classic case that you can’t easily type:

const data = JSON.parse(userDataSource);

So you might end up typing it in some way such as:

interface UserData {
name: string;
age: number;
email: string;
}
const data = JSON.parse(userDataSource) as UserData;

This can work but you can’t always ensure the shape of the object in this input string. Furthermore, this is again just compile-time type checking and not runtime type checking, for which you’ll need to use a strict validation schema.