Type Safety at Runtime in Typescript

Rate this content
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.

This talk has been presented at TypeScript Congress 2022, check out the latest edition of this JavaScript Conference.

FAQ

Runtime type safety in TypeScript refers to the validation of data types at runtime, ensuring that the data conforms to the expected types defined during development. TypeScript does not natively support runtime type checking, so developers must use runtime validators or schema validators to ensure type safety.

TypeScript does not include runtime type checking as part of its design goals. The TypeScript team decided early on, around 2014, to focus on static type checking and compile-time validation, leaving runtime type checking outside of its core functionality.

There are several libraries available for runtime type validation in TypeScript, including Yap, AJV, Zad, IOTS, and Runtypes. These libraries offer different features and performance benchmarks, helping developers implement runtime type safety in their projects.

Performance of runtime type validation libraries can be assessed by referencing the 'TypeScript runtime type benchmarks' repository on GitHub. This resource provides statistics and performance benchmarks for various libraries, helping developers choose the one that best fits their needs.

Schema validators in TypeScript play a crucial role in ensuring runtime type safety. They validate the structure and type of runtime data against predefined schemas, helping to catch type errors and mismatches that occur during execution, which are not detected during static type checking.

Zad library in TypeScript allows developers to define schemas using primitive schemas for basic types like string, number, and boolean. It also supports complex data structures such as objects and arrays. Developers can validate data at runtime using these schemas and handle errors effectively using methods like 'parse' and 'safeParse'.

Yes, the Zad library supports reusability of schemas through combinators that allow for extending, merging, and modifying schemas. This feature enables developers to efficiently manage and scale their type validation logic across different parts of their application.

GitHub stars are often used as a metric to gauge the popularity and community support of open-source libraries. A higher number of stars may indicate a reliable and widely-used library, which can be a helpful criterion when developers are selecting tools for their projects.

Kajetan Świątek
Kajetan Świątek
8 min
29 Apr, 2022

Comments

Sign in or register to post your comment.
Video Summary and Transcription
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

React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced 2022React Advanced 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced 2021React Advanced 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Alex introduces tRPC, a toolkit for making end-to-end type-safe APIs easily, with auto-completion of API endpoints and inferred data from backend to frontend. tRPC works the same way in React Native and can be adopted incrementally. The example showcases backend communication with a database using queries and validators, with types inferred to the frontend and data retrieval done using Prisma ORM.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
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.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced 2022React Advanced 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
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.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.