Validating external data and TypeScript with Node
This is the lesson that separates code that looks safe from code that is. TypeScript checks types at compile time, but external data arrives at runtime: API responses, JSON files, environment variables, command-line arguments, forms. None of that data goes through the compiler. If you declare that something is of some type without checking it, the compiler believes you and the error appears late and far away. The solution is to validate at the boundary: turn an unknown into a known type only after checking it.
Validating by hand with a type guard
The most basic technique is a type guard that inspects the value. First you check that it is a non-null object, then that each property exists and has the expected type. If everything matches, you return true and the compiler lets you use it with the real type. Writing these guards by hand is useful to understand the mechanism, but it becomes long and error-prone when the data is complex, because the type and the validation can drift apart.
interface Todo {
id: number;
title: string;
completed: boolean;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isTodo(value: unknown): value is Todo {
return (
isRecord(value) &&
typeof value.id === 'number' &&
typeof value.title === 'string' &&
typeof value.completed === 'boolean'
);
}
function parseTodos(json: string): Todo[] {
const data: unknown = JSON.parse(json);
if (!Array.isArray(data) || !data.every(isTodo)) {
throw new Error('Invalid todo list');
}
return data;
}
console.log(parseTodos('[{"id":1,"title":"Test","completed":false}]'));
// parseTodos('[{"id":"x"}]'); // throws: Invalid todo listSchema libraries
In real projects a validation library is used, such as Zod, Valibot or ArkType. The idea is to declare a schema once and get from it both the runtime validator and the static type, so they cannot drift apart. For example, with Zod you define z.object({ id: z.number(), title: z.string() }), call schema.parse(data) and get an already typed value, and with z.infer<typeof schema> you extract the type. You need to install the library with npm. API details change between versions, so check the official documentation of the one you choose; the principle is the same as in the manual guard.
TypeScript with Node.js
To run TypeScript in Node you have three paths. The first is to compile with tsc and run the JavaScript in dist, the most robust for production. The second is tsx, perfect in development for its speed, although it does not check types. The third is recent versions of Node, which can run .ts files directly by erasing types, with certain restrictions: they do not support enum or constructor parameter properties, and they require import type where appropriate. In any of the three, always run tsc --noEmit in your workflow or in continuous integration, because it is the only thing that truly checks the types. With @types/node, the data in process.env is string | undefined and the process.argv arguments are string[]: validate them like any other external data.
import { readFileSync, existsSync } from 'node:fs';
interface Settings {
port: number;
name: string;
}
function isSettings(value: unknown): value is Settings {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as Record<string, unknown>).port === 'number' &&
typeof (value as Record<string, unknown>).name === 'string'
);
}
function loadSettings(path: string): Settings {
if (!existsSync(path)) {
return { port: Number(process.env.PORT ?? 3000), name: 'default' };
}
const data: unknown = JSON.parse(readFileSync(path, 'utf8'));
if (!isSettings(data)) {
throw new Error('Invalid settings file: ' + path);
}
return data;
}
const arg = process.argv[2] ?? 'settings.json';
console.log(loadSettings(arg));✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères