Type Safety at Runtime in Typescript

Bookmark

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

Comments

Sign in or register to post your comment.

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 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 
React Summit 2023React Summit 2023
19 min
7 TypeScript Patterns You Should Be Using
In this talk, we will be going over a number of common useful and best-practice-proven TypeScript patterns to use in React 18. This includes how to correctly type component properties, children and return types, using React's built-in types, typing contexts, and the usual enum rant (but constructively).
TypeScript Congress 2022TypeScript Congress 2022
27 min
TypeScript and the Database: Who Owns the Types?
We all love writing types in TypeScript, but we often find ourselves having to write types in another language as well: SQL. This talk will present the choose-your-own-adventure story that you face when combining TypeScript and SQL and will walk you through the tradeoffs between the various options. Combined poorly, TypeScript and SQL can be duplicative and a source of headaches, but done well they can complement one another by addressing each other's weaknesses.

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Workshop Free
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
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 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
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
Node Congress 2021Node Congress 2021
245 min
Building Serverless Applications on AWS with TypeScript
Workshop
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:
https://excalidraw.com/#room=57b84e0df9bdb7ea5675,HYgVepLIpfxrK4EQNclQ9w
DynamoDB blog Alex DeBrie: https://www.dynamodbguide.com/
Excellent book for the DynamoDB: 
https://www.dynamodbbook.com/
https://slobodan.me/workshops/nodecongress/prerequisites.html


TypeScript Congress 2022TypeScript Congress 2022
118 min
Crash Course into TypeScript for content from headless CMS
Workshop Free
In this workshop, I’ll first show you how to create a new project in a headless CMS, fill it with data, and use the content in your project. Then, we’ll spend the rest of time in code, we will:
- Generate strongly typed models and structure for the fetched content.
- Use the content in components
- Resolve content from rich text fields into React components
- Touch on deployment pipelines and possibilities for discovering content-related issues before hitting production
Node Congress 2022Node Congress 2022
57 min
Writing Universal Modules for Deno, Node and the Browser
Workshop
This workshop will walk you through writing a module in TypeScript that can be consumed users of Deno, Node and the browsers. I will explain how to set up formatting, linting and testing in Deno, and then how to publish your module to deno.land/x and npm. We’ll start out with a quick introduction to what Deno is.