iTranslated by AI
Types, Values, and Validation in TypeScript
TypeScript is essentially just JavaScript that merely thinks it has types attached to it.
No matter how many types you add, they will never affect the runtime.
In code reviews, I see so many people who misunderstand this. I've explained it many times, but since it doesn't seem to be sticking, I decided to write an article from the perspective of validation in TypeScript.
Also, I have a friend trying to build various things using validators in TS, and another who just started programming and is using Zod and OpenAPI, so they are the intended audience.
Namespaces for Types and Values
Namespaces (scopes) in TypeScript can be classified into two categories:
- Values: Things that exist in memory on the runtime.
- Types: Things that can only be referenced during static analysis. They completely disappear during compilation.
TypeScript basically has syntax that is a superset of JavaScript, and the conversion from TypeScript to JavaScript refers to the process of erasing type annotations, such as : number in const x: number = 1;.
Due to the characteristic of erasing types at runtime, TypeScript type annotations do not exist as values at all.
For example, in Scala's Manifest types or Ruby's Sorbet, where types are defined via DSL as part of the runtime, types exist as values, but this does not happen in TypeScript.
Specific syntaxes that affect only the type namespace include import type, type, interface, implements, as, satisfies, etc.
import type { Foo } from "./foo";
type Bar = { bar: number };
interface Baz extends Bar { baz: string }
// @ts-expect-error
console.log(Foo, Bar, Bar);
class X implements Baz {
bar = 1;
baz = 'x';
}
Conversely, with some exceptions, values cannot be used as types as they are. If you want to use them, you need to use typeof in the type namespace.
const foo: number = 1;
type Foo = typeof foo;
const add = (a: number, b: number): number => 1;
type AddType = typeof add; //-> (a: number, b: number) => number;
Note that the typeof used in this type namespace is different from the runtime typeof.
const t = 1;
console.log(typeof t); //=> "number"
type T = typeof t; //=> number as a TypeScript type
This value-level typeof is not expressive enough to restore TypeScript's type information. It can only tell you things like whether it's a primitive type like number, string, or boolean, or whether it's an object type or not.
The unique thing about TypeScript is that it is a statically typed language that is converted into a dynamically typed language. Beginners often misunderstand this, but dynamically typed languages don't lack types; rather, types are attached at runtime. typeof is a language feature to retrieve the runtime type.
Type scopes have lexical closures, just like value scopes.
type X = number;
{
type Y = number;
{
type Z = number;
}
// @ts-expect-error
const v: Z = 1;
}
const v: X = 1;
Classes that Generate Both Types and Values
I mentioned that TypeScript distinguishes between types and values, but classes behave a bit specially.
class Point {
constructor(public x: number, public y: number) {}
}
const p1: Point = new Point(1, 2);
The class syntax defines both a value as a constructor named Point and a type for the instance named Point simultaneously.
Therefore, while the following code works, it behaves slightly differently at runtime.
const p1: Point = new Point(1, 2);
const p2: Point = {x: 1, y: 2};
console.log(p1 instanceof Point, p2 instanceof Point); // => true, false
instanceof is also a built-in JavaScript feature; it returns true if a value was instantiated from a class via new (strictly speaking, if they share the same prototype) and false otherwise.
The reason p2 instanceof Point is false is that while it satisfies the interface of Point as a type, the process of creating the value is different.
Note that the Point type is not the type of the Point value. The following code will fail:
// @ts-ignore
class Point2: Point = Point;
To understand this, let's look at the following code:
class X {
constructor(private v: number) {}
}
const XConstructor: typeof X = X;
type XInstance = InstanceType<typeof X>;
const x: XInstance = new XConstructor(1);
This code passes type checking. It's code that explicitly extracts the constructor type and the instance type from X and uses them to create an instance.
Also, it is possible to define an object type that can be instantiated with new without using the class syntax.
class X {
constructor(private v: number) {}
}
declare const X2: {
new(v: number): X;
};
const x2: X = new X2(1);
declare is a feature used to declare that a symbol exists in the value namespace. This is mainly used when symbols accessible as global variables are defined, and the programmer must separately guarantee that they actually exist at runtime. (It is not a feature you should use aggressively.)
Conversely, an abstract class, which is declared as a class that cannot be used without being inherited, always exists as a constructor value despite its name. TypeScript merely imposes a constraint that it cannot be directly instantiated with new, but it is possible at runtime.
abstract class X {}
// @ts-ignore
const x = new X();
The relationship between classes, values, and types is something that people coming from Java/C# sometimes misunderstand, especially regarding the behavior of type casting. I occasionally see code in React Native mobile apps where this understanding is a bit shaky.
enum
Like classes, enum is a syntax that defines both a type and a value simultaneously.
enum E {
A,
B,
C
}
const e: E = E.A;
This expands into the following value:
var E;
(function (E) {
E[E["A"] = 0] = "A";
E[E["B"] = 1] = "B";
E[E["C"] = 2] = "C";
})(E || (E = {}));
The enum is a TypeScript-specific feature that does not exist in JavaScript syntax and has been around since the early releases.
With this, TS breaks the implicit rule of not extending JavaScript syntax beyond types, but it continues to be used because it is convenient. It's too late to remove it now...
However, it generates a significant amount of code and doesn't play well with bundlers or minifiers, so it's best avoided if you're concerned about build size.
This can be rewritten using union types as follows:
const A = 0;
const B = 1;
const C = 2;
type E = typeof A | typeof B | typeof C;
const v: E = A;
Alternatively, you can use const enum, which is erased during compilation. I personally prefer this.
const enum E {
A,
B,
C
}
const e: E = E.A;
// const e = 0 /* E.A */;
However, with const enum, the ability to retrieve a key from a value is lost.
E[E.A] // => "A"
Since this is mainly useful for debugging, I usually use const enum and only remove const when debugging.
Types Cannot Be Carried Over to Runtime
Since TypeScript is a language that is executed after being converted to JavaScript, all static type information as TypeScript is lost during the conversion to JS.
Additionally, (unless you use a special compiler plugin), there is no way to know at runtime what type information has been assigned to a symbol.
Ultimately, TypeScript is nothing more than JavaScript that merely thinks it has types, and in reality, at runtime, you can write as much code as you want that violates TypeScript's inference state. Scary, isn't it?
The only countermeasure at the user level is to write well-behaved code that matches TypeScript's inference state. This means things like avoiding any, avoiding @ts-ignore, and avoiding upcasting with as.
Value Validation and Type Inference
As mentioned earlier, TypeScript is JavaScript that thinks it has types. In other words, simply adding types does not mean you are actually validating the values.
While not validating values within the scope of your own code is a matter of self-responsibility, the problem lies in validating data passed across system boundaries. For example, a request payload on a server.
type User = {
name: string;
age: number;
};
export function onFetch(req: Request) {
// Casting any to User, but
// does this really satisfy the User type?
const user: User = await req.body();
...
}
Since types can be inferred from values, it is possible to assemble a schema at runtime and extract the type as an inference from it. A prominent example of this is Zod.
Note for beginners: If you are developing both the client and the server yourself, you might wonder if a request that violates the types could actually exist. Remember that in reality, anyone can use the browser's Devtools (F12). By using fetch(...) in Devtools, a service user can create any request they want. Keep in mind that someone with malicious intent to break the service will create and send arbitrary data from here. Although I used Devtools for this explanation, the same is possible with any HTTP client.
zod
import {z} from "zod";
const schema = z.object({
name: z.string(),
age: z.number(),
});
type User = z.infer<typeof schema>;
const parsed = schema.safeParse({ name: "John", age: "25" });
if (parsed.success) {
const user: User = parsed.data;
}
You can extract the type corresponding to the schema definition using z.infer<typeof schema>.
It is possible to use this for validation while ensuring that the parsed data satisfies the type.
jsonschema
JSON Schema is a schema definition for expressing constraints on JSON, and it is not directly related to TypeScript.
There is a specification, and there are validator implementations for it; the most widely used one is (probably) Ajv.
Here is a pattern where you write a JSON Schema that corresponds to a type using Ajv:
import { JSONSchemaType, Ajv } from "ajv";
const ajv = new Ajv();
type User = {
name: string;
age: number;
}
const schema: JSONSchemaType<User> = {
type: "object",
required: ["name", "age"],
properties: {
name: { type: "string" },
age: { type: "number" },
},
additionalProperties: false,
};
const validate = ajv.compile(schema);
const user: unknown = { name: "John", age: "25" };
if (validate(user)) {
const u: User = user;
}
While this works, having to manually write the JSON corresponding to the type is somewhat tedious. Honestly, it should be obvious, but since you can't extract values from types, you are forced to write it this way if you want to stay within TypeScript alone, which cannot expand values from types.
Another approach is to generate type definitions from an existing JSON Schema. For example, json-schema-to-typescript.
$ npx json-schema-to-typescript -i schema.json
export interface Schema {
name: string;
age: number;
[k: string]: unknown;
}
This also seems okay, but it's a bit annoying that the workflow requires regenerating the type definitions with this CLI every time you modify the JSON Schema.
Conversely, it's not that difficult to write code yourself that infers TypeScript types from a JSON Schema.
export type JSONSchema = {
type: 'string' | 'number' | 'boolean' | 'object' | 'array';
description?: string;
properties?: {
[key: string]: JSONSchema;
};
items?: JSONSchema;
required?: readonly string[];
};
type ToType<T> = T extends { type: 'string' }
? string
: T extends { type: 'number' }
? number
: T extends { type: 'boolean' }
? boolean
: T extends { type: 'array'; items: infer U }
? ToType<U>[]
: T extends { type: 'object'; properties: infer P; required: infer R extends readonly string[] }
? { [K in keyof P]-?: K extends R[number] ? ToType<P[K]> : ToType<P[K]> | undefined }
: never;
export type SchemaToType<T extends JSONSchema> = ToType<T>;
// usage
const schema = {
type: 'object',
required: ['name', 'age'],
properties: {
name: {
type: 'string'
},
age: {
type: 'number'
}
}
} satisfies JSONSchema;
type User = SchemaToType<typeof schema>;
const user: User = {
name: 'john',
age: 25
}
There are tools to generate JSON Schema from TypeScript implementations, but in my experience, they are all a bit underwhelming.
Since it involves semantic analysis of TypeScript, the implementation is quite difficult...
Every approach has its pros and cons.
openapi
OpenAPI (Swagger) is a specification for describing URL endpoints and the JSON Schema handled by those paths.
openapi: 3.0.0
info:
version: 1.0.0
title: Sample API
description: A sample API to illustrate OpenAPI concepts
paths:
/list:
get:
description: Returns a list of stuff
responses:
'200':
description: Successful response
You can generate TypeScript type definitions from this and create type definitions for an HTTP client.
$ npx openapi-typescript spec.yaml -o spec.d.ts
Using this, you can create a type-defined HTTP client.
import type { paths } from "./spec.d.ts";
import { Fetcher } from 'openapi-typescript-fetch';
const fetcher = Fetcher.for<paths>()
fetcher.configure({
baseUrl: 'http://localhost:8000',
});
const list = fetcher.path('/list').method('get').create();
await list({});
JSON and the JSON Schema that types it are like common specifications independent of language, so being able to handle them is very versatile.
There is also tRPC specifically for TypeScript, but I haven't used it, so I'll just mention it.
node:util's parseArgs
parseArgs is a validator for CLI arguments. In a Node environment, you can infer types by using it together with @types/node.
import { parseArgs } from "node:util";
const parsed = parseArgs({
allowPositionals: true,
args: process.argv.slice(2),
options: {
foo: {
type: "string",
short: "f",
},
} as const,
});
type Options = typeof parsed["values"];
//=> { foo: string | undefined; }
It's a shame that it results in string | undefined even if you provide a default, but I use it regularly.
It can also be used in Deno. Actually, I wrote an issue and had it added.
What is Important in a Validator
While I have introduced various implementations, the important thing is to be mindful of the "Single Source of Truth"—ensuring that the master schema definition is unique. If you define different validators or types for the same target in multiple places, they will inevitably diverge, leading to issues.
Also, the purpose of validation varies depending on the environment, and different validation implementations are required as a result:
- Server-side validation is for security.
- Frontend validation is for early discovery of form input errors without querying the server; it is not for security.
- Since the frontend has its own state, types generated from the server cannot satisfy everything.
- The JSON Schema required for OpenAI's Function Call is for AI documentation, where the
descriptionis as important as the type itself.
Note that the semantics expressible in JSON Schema and TypeScript (or other languages) do not correspond strictly 1:1. For example, in JSON Schema, "type": "int" allows for min/max constraints to limit numerical values, but mapping this to a type requires a language with a special type system like dependent types; in TypeScript, it simply becomes a number type. In fact, in JavaScript, there is no distinction between integers and floating-point values.
While I focused on validation this time, I believe that writing code while being conscious of both types and values is the key to using TypeScript safely.
Why Do We Write Types in TypeScript?
The reason we use TypeScript under such constraints in the first place is that we want to use it as documentation that can be automatically checked. Personally, I feel it is more accurate to think of TypeScript as a type-checking linter rather than a compiler.
As for language design, TypeScript is a language that chose rich expressiveness even at the cost of safety. This is a result of the reality where the target JavaScript is dynamically typed, and the ecosystem provided uninhibited APIs and DSLs that didn't consider types (e.g., jQuery). In response, both the expressiveness to force types upon them and escape hatches for when types couldn't be satisfied were required. While these specifications would never be chosen if building a language from scratch, they meet the demands that occur in reality.
TypeScript's implementation doesn't necessarily have a single consistent policy; rather, it has a history of being expanded to interpret real-world use cases in the world of types as a shadow of JavaScript. Therefore, I believe it is an incredibly difficult language to teach to beginners who aren't familiar with those use cases.
Summary
- TypeScript type annotations disappear at runtime.
- Classes and enums, which generate both types and values simultaneously, are special entities in TypeScript.
- To perform value validation in TypeScript, you have no choice but to define a schema as a value.
- It is possible to generate types from value inference results, but not the other way around.
- Type annotations are an executable linter.
Discussion