Type Safety at Runtime in Typescript

Rate this content

We all know, that TypeScript helps us in many ways. The compiler guides us during our work, ensuring, that every piece of data falls into a given place.

But there are some limitations. TypeScript was meant to help us during development time. After the compilation step, we still cannot be 100% sure what can happen during runtime...

Unless we do something about that and defend ourselves against unwanted runtime errors! This talk serves as an introduction to the problem and explains how we can face it to make our applications more error-proof.

8 min
29 Apr, 2022

AI Generated Video Summary

TypeScript does not have runtime type checking, but there are libraries available for runtime type validation. ZAD is a popular runtime type validation library in the React ecosystem, offering schema primitives for specific validations on primitive types and support for complex data like objects and arrays. ZAD also provides methods for parsing values and handling successful or failed parsing with error objects.

1. Introduction to TypeScript and Runtime Types

Short description:

Hello everyone, today I'd like to walk you through a very cool topic around TypeScript, so type safety at runtime. TypeScript is not perfect and will never meet all expectations of all users. In the early stages of TypeScript, there was a question about having a runtime type system, but it was stated that runtime type checking remains outside the design goals. TypeScript compiles down to JavaScript, so there is no runtime validation for types. One potential solution is to use runtime types or validators, and there are multiple libraries available. You can choose a library based on criteria such as performance and popularity. The top five runtime types libraries by GitHub stars are Yap, AJV, Zad, IOTS, and Runtypes.

Hello everyone, today I'd like to walk you through a very cool topic around TypeScript, so type safety at runtime, but before that, I'd like to introduce myself. I'm Kejtan Świątek, I'm a front-end developer from Wrocław, and you can find my work on either Twitter, at kejtansw, or on my blog kejtan.dev, when I occasionally write about front-end functional programming and stuff I learn along the way.

Let me start this presentation by stating that TypeScript is not perfect, and I know it's a pretty bold statement, considering this is a TypeScript conference, and I hope organisers won't ban me for life because of it, but what I mean is that TypeScript, like any other tool, will never meet all expectations of all of its users. And in the early stages of TypeScript, one of the expectations was to have a runtime type system, and the community asked whether is it a missing piece of the TypeScript ecosystem. And this question was answered pretty early and in 2014 it was stated that runtime type checking remains outside of the design goals for TypeScript. And as you can see, it had pretty mixed feelings from the community. But I think after eight years since that answer, this pretty much settled in in our minds as TypeScript developers. And we got pretty much used to the fact that TypeScript underneath is just plain JavaScript. And what I mean by that is that after our work with our code is done, it compiles down to JavaScript to be interpreted by different runtimes like Node.js or our browsers. So we got rid of all our interfaces and typefaces. So we have no runtime validation for our types.

And the simplest example of that may be fetching some data from external APIs. So this is a common code in our TypeScript projects. We have an interface for our runtime data. We fetch this data from some API and parse the response to a JSON payload. But you can see in line 7 that we declared that our runtime value is of type Hero, but the question here is how sure are we that the return object here is really of type Hero? And I can assure you that in this example, we are not 100% sure about that. So what's the potential solution to this problem? This might be runtime types, also known as runtime validators or schema validators or JSON decoders. And what about TypeScript ecosystem? Like with almost every issue, we can either implement it ourselves or use a library for it. And fortunately for runtime types or runtime validators, there are multiple libraries doing just that. And we're choosing a library that suits your needs. There are different criteria that you can use. For example, performance of such parsing. And the best resource for that is called TypeScript runtime type benchmarks. And it's a GitHub repository and you can find it under the QR code here in the corner. And basically it gives you a different statistic around different types of parsing and type assertion, and gives you a performance benchmarks of those for different libraries. And like with every other library, the other criteria you can use for finding the one that suits your needs is popularity. And we all like measuring popularity by GitHub stars. So here you have it, top five runtime types libraries by number of GitHub stars. And those are Yap, AJV, Zad, IOTS, and Runtypes. Here I would like to give you a small preview of one of those libraries.

2. ZAD: Runtime Type Validation Library

Short description:

ZAD is a runtime type validation library that is often used in the React ecosystem. It provides schema primitives for JavaScript and TypeScript, allowing for specific validations on primitive types like strings and numbers. ZAD also supports creating schemas for complex data like objects and arrays, with the ability to extract inferred types from the created schema. Additionally, ZAD offers combinators for extending and merging object schemas, as well as picking and omitting fields. In practice, ZAD provides methods like parse and SaveParse for parsing values and handling successful or failed parsing with error objects.

And for that I've chose ZAD. And not because it's the most performance one of or most popular, it's just because it comes out pretty often in the React ecosystem and also it has pretty simple API.

Starting from basics. ZAD has something called schema primitives, so primitive schemas for every primitive type of JavaScript and TypeScript like string, number, boolean, even date, or empty type like undefined or null. And from that we can be more specific. For example, create a schema for a string that has a maximum number of characters or or has an email format or URL format, something like that. And for numbers as well, like a number greater than some value or lower than some value or an integer value and many other specific methods for those schema primitives.

We can also create schemas for more complex data like objects or arrays. For example, with the object method, we create our schema for the dog type by passing the desired structure with name and age. But instead of values, we pass the primitive schemas for those fields. What's also cool about Zot is also that we can extract the inferred type out of the created schema, so we can create a type of dog by using the inferred type from Zot. If you are also interested in reusing our schemas, there are some combinators for extending and merging object schemas and for picking and omitting some fields out of the object schema.

How can we use our schemas in practice? So, for example, let's create a schema for a basic string type. Then we can use the parse method to parse our value. So we passed our runtime value and if the parsing is successful, it just returns our value untouched. But if it's failing, it shows a Zot error. But if we don't like to throw errors around, we can use SaveParse method and it returns an object with an information whether the parsing was successful or not. And if it is, it returns our data as a payload or our error object if the parsing fails.

That's all from my side. I gave you all the theory behind runtime validators, I gave you a list of potential solutions and also introduced you to one of it. And now it's your turn to try it out in your project.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.
TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.

Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Featured Workshop
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.
Node Congress 2021Node Congress 2021
245 min
Building Serverless Applications on AWS with TypeScript
This workshop teaches you the basics of serverless application development with TypeScript. We'll start with a simple Lambda function, set up the project and the infrastructure-as-a-code (AWS CDK), and learn how to organize, test, and debug a more complex serverless application.
Table of contents:        - How to set up a serverless project with TypeScript and CDK        - How to write a testable Lambda function with hexagonal architecture        - How to connect a function to a DynamoDB table        - How to create a serverless API        - How to debug and test a serverless function        - How to organize and grow a serverless application

Materials referred to in the workshop:
DynamoDB blog Alex DeBrie: https://www.dynamodbguide.com/
Excellent book for the DynamoDB: https://www.dynamodbbook.com/