Analyzing Requirements
I'm currently focused on the core purpose of the proposed TypeScript library: robust runtime type validation. I'm exploring the specific functional needs and how the library would ideally interact with existing TypeScript features. The focus is on ensuring a smooth developer experience and practical use cases for validating data at runtime.
Prioritizing Tree-Shaking
I've decided to prioritize tree-shaking support to minimize the library's impact on application size. My chosen strategy involves building a lightweight functional schema validator. This approach will demonstrate a practical implementation of runtime type validation in a composable and modular way, meeting the core requirements without resorting to potentially bulky reflection-based solutions.
Designing Validators
My focus is now on the core of the library: the actual runtime validation functions. I'm prioritizing creating primitives like str, num, and bool, and composites such as object and array. I'm also considering a Zod-like infer utility for deriving TypeScript types. I'm currently drafting code using the Validator type.
Planning Implementation Steps
I'm now outlining a clear implementation plan, breaking the library's development into manageable steps. This will make it easier to stay focused on creating a usable library. First, project setup and core logic will be my focus, with a schema builder as the foundation. I also aim to set up the build configuration using tsup. After that, I will work on usage examples to prove the library works as expected. I will focus on simplicity, and will throw errors or return values, instead of using a Result pattern.
Defining Function Exports
I'm now iterating on the library's exports, ensuring maximum tree-shaking efficiency. I've realized that distinct, functional exports are key, and have specified module: "esnext" and moduleResolution: "bundler" in my tsconfig.json. Also, the sideEffects: false flag in package.json is essential, and acts as the "magic switch" for bundling. I'm focusing on crafting primitives like string() and number(), an object validator that iterates keys, and an Infer helper for deriving TypeScript types.
Defining Exports Strategy
I'm now putting the finishing touches on the library's design. The key is crafting focused functions like string() and object(). I've added comments to tsconfig.json explaining the reasons behind specific configurations. In terms of bundling, tsup makes the dual CJS/ESM build incredibly simple. The package.json now includes sideEffects: false.
This is a guide to building a composable, lightweight runtime validation library (similar to Zod) that is optimized for tree-shaking.
To achieve tree-shaking, we will use Functional Composition instead of massive Classes, and we will configure package.json to tell bundlers that our files have no side effects.
Prerequisites
mkdir type-safe-lib
cd type-safe-lib
npm init -y
npm install -D typescript tsup
1. File Structure
type-safe-lib/
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── src/
├── index.ts
├── core.ts # Base types and inference helper
├── primitives.ts # validators for string, number, boolean
└── complex.ts # validators for object, array
2. Implementation (src/)
We will build a system where you import only what you need. If you only import string(), the code for object() will be removed from the final bundle.
src/core.ts
Defines the base structure and the Type Inference helper.
export type ParseResult<T> =
| { success: true; data: T }
| { success: false; error: string };
export interface Schema<T> {
parse: (input: unknown) => T;
safeParse: (input: unknown) => ParseResult<T>;
_output: T; // Ghost property for type inference
}
// The utility to extract TypeScript types from our runtime schemas
export type Infer<S extends Schema<any>> = S['_output'];
export function createSchema<T>(validator: (input: unknown) => T): Schema<T> {
return {
_output: undefined as any,
parse: (input) => validator(input),
safeParse: (input) => {
try {
return { success: true, data: validator(input) };
} catch (e) {
return { success: false, error: e instanceof Error ? e.message : String(e) };
}
},
};
}
src/primitives.ts
Simple value checkers.
import { createSchema } from './core';
export const string = () => createSchema<string>((input) => {
if (typeof input !== 'string') throw new Error('Expected string');
return input;
});
export const number = () => createSchema<number>((input) => {
if (typeof input !== 'number' || Number.isNaN(input)) throw new Error('Expected number');
return input;
});
export const boolean = () => createSchema<boolean>((input) => {
if (typeof input !== 'boolean') throw new Error('Expected boolean');
return input;
});
src/complex.ts
Recursive validators for Objects and Arrays.
import { createSchema, type Schema, type Infer } from './core';
export const array = <T>(schema: Schema<T>) => createSchema<T[]>((input) => {
if (!Array.isArray(input)) throw new Error('Expected array');
return input.map((item, i) => {
try {
return schema.parse(item);
} catch (e) {
throw new Error(`at index [${i}]: ${(e as Error).message}`);
}
});
});
export const object = <T extends Record<string, Schema<any>>>(shape: T) => {
type ObjectType = { [K in keyof T]: Infer<T[K]> };
return createSchema<ObjectType>((input) => {
if (typeof input !== 'object' || input === null) throw new Error('Expected object');
const result: any = {};
const record = input as Record<string, unknown>;
for (const key in shape) {
try {
result[key] = shape[key].parse(record[key]);
} catch (e) {
throw new Error(`at key "${key}": ${(e as Error).message}`);
}
}
return result;
});
};
src/index.ts
The entry point.
export { Infer } from './core';
export * from './primitives';
export * from './complex';
3. Configuration for Tree-Shaking
This is the most critical part for your requirement.
package.json
We must set "sideEffects": false. This tells tools like Webpack, Rollup, and ESBuild that importing files from this library does not trigger global logic (like polyfills). This gives them permission to remove unused exports.
{
"name": "my-type-safe-lib",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "tsup"
},
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.0.0"
}
}
tsup.config.ts
We use tsup to bundle the library. It uses esbuild under the hood, generates type definitions (d.ts), and creates both ESM (for modern apps) and CJS (for legacy node) formats.
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts'],
format: ['cjs', 'esm'], // Build for Node and Modern Web
dts: true, // Generate .d.ts files
splitting: false,
sourcemap: true,
clean: true,
minify: true, // Minify output
treeshake: true, // Remove dead code during build
});
4. Usage & Verification
Here is how a consumer would use the library.
import { object, string, number, type Infer } from 'my-type-safe-lib';
// 1. Define Schema
const UserSchema = object({
id: number(),
username: string(),
email: string(),
});
// 2. Get automatic TypeScript type
// Type is: { id: number; username: string; email: string; }
type User = Infer<typeof UserSchema>;
// 3. Runtime Validation
const dataFromApi = { id: 1, username: "alice", email: "alice@example.com" };
// Returns valid object or throws error
const user = UserSchema.parse(dataFromApi);
console.log(user.username); // TypeScript knows this is a string
Why is this Tree-shakeable?
- Functional Exports: We export
string, number, object individually. Check this scenario:
import { string } from 'my-type-safe-lib';
string().parse("hello");
Because you didn't import object or array, the bundler sees they are unused.
- SideEffects: False: The
package.json flag guarantees the bundler that dropping complex.ts won't break the application.
- ESM Format: We generate native ES Modules (
dist/index.js) which allows static analysis by bundlers.
How to verify Tree-Shaking
- Run
npm run build.
- Create a file
test-shake.js:
import { string } from './dist/index.js';
console.log(string().parse('test'));
- Run a bundler (like
esbuild) on this test file with bundling enabled.
- Inspect the output code. You will search for the error message
"Expected object" (which is inside object() implementation).
- If tree-shaking is working, that string will NOT exist in the output bundle.