Improve TypeScript type performance
Improve TypeScript type performance
Problem
The Schema Benchmarks TypeScript page counts how much work the TypeScript compiler does for each library. It measures how many type instantiations it takes to declare the same product schema and read its input and output types. Valibot is one of the most expensive libraries there:
| Library | Instantiations | Characters on hover |
|---|---|---|
| zod | 1,185 | 660 |
| superstruct | 1,254 | 2,056 |
| effect@rc | 1,632 | 885 |
| zod/mini | 1,640 | 958 |
| runtypes | 4,995 | 868 |
| valibot | 8,539 | 2,732 |
| sury | 10,619 | 884 |
| arktype | 28,869 | 447 |
A selection of libraries, with numbers from the site at the time of writing (Valibot 1.5.0, TypeScript 6.0.3). Valibot ranks 12th of the 17 libraries that infer types.
Almost all of the cost is in declaring the schema: 7,889 instantiations. Reading InferInput and InferOutput adds only about 650.
Why it matters
Instantiations are what turn into slow editor feedback and slow builds as a codebase adds more schemas. Valibot is often chosen for its small bundle size and modular design. Poor type performance works against that choice in large projects. The type on hover is also the longest in the comparison, and the same text appears in every error message that mentions the schema.
Benchmark schema
The benchmark uses this schema (source):
const imageSchema = v.object({
id: v.number(),
created: v.date(),
title: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
type: v.picklist(['jpg', 'png']),
size: v.number(),
url: v.pipe(v.string(), v.url()),
});
const ratingSchema = v.object({
id: v.number(),
stars: v.pipe(v.number(), v.minValue(1), v.maxValue(5)),
title: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
text: v.pipe(v.string(), v.minLength(1), v.maxLength(1000)),
images: v.array(imageSchema),
});
const schema = v.object({
id: v.number(),
created: v.date(),
title: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
brand: v.pipe(v.string(), v.minLength(1), v.maxLength(30)),
description: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
price: v.pipe(v.number(), v.minValue(1), v.maxValue(10000)),
discount: v.nullable(v.pipe(v.number(), v.minValue(1), v.maxValue(100))),
quantity: v.pipe(v.number(), v.minValue(0), v.maxValue(10)),
tags: v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(30))),
images: v.array(imageSchema),
ratings: v.array(ratingSchema),
});The measurement method is in bench/src/scripts/types/probe.ts. It uses the TypeScript compiler API and reads program.getInstantiationCount() before and after declaring the schema.
Expected outcome
- Fewer type instantiations for common schemas built with
object,array,nullableandpipewith validation actions. - Inferred input, output and issue types stay unchanged.
- Ideally, a type performance check in CI so that regressions are caught.
Related
- #1374
- #1442
Source: open-circle/valibot