Create a TypeScript utility library that includes runtime type checking and tree-shaking…
- User
Create a TypeScript utility library that includes runtime type checking and tree-shaking support.
Assistant
The user wants a TypeScript utility library with two specific features:
- Runtime type checking: TypeScript types disappear at runtime. The user needs a way to validate data (like API responses, configs) while the code is running.
- Tree-shaking support: The library should be modular so that modern bundlers (like Webpack, Rollup, esbuild) can remove unused code, keeping the final bundle size small.
Key Components to Implement:
-
Project Structure: A standard library structure (src, dist, package.json, tsconfig.json).
-
Runtime Type Checking Strategy:
- Option A: Classes/Decorators. (A bit old school, heavy).
- Option B:
instanceofchecks. (Limited, doesn't handle plain JSON objects well). - Option C: Schema-based validation. (Flexible, works well with JSON).
- Option D: Zod/IO-TS style (Type inference from schemas). This is the modern standard for "TypeScript utility libraries." It ensures the static types match the runtime validators.
I will choose a simplified implementation of Option D. I'll create a lightweight schema system where you define a schema, and it generates both a validator and a TypeScript type.
-
Tree-shaking Strategy:
- Use ES Modules (
"type": "module"inpackage.jsonor.mjsextension, or just proper TS compilation to ESM). - Export individual functions/modules rather than one giant namespace object.
- Use
package.jsonfields likesideEffects: falseand properexportsmap.
- Use ES Modules (
-
Code Content:
- Core Types:
Result(Success/Failure) to handle validation errors without throwing exceptions immediately (functional approach). - Primitives:
string,number,boolean. - Composites:
object,array. - Utilities:
parse,is(type guard).
- Core Types:
Step-by-Step Implementation Plan:
- Step 1: Setup files.
package.json,tsconfig.json. - Step 2: The Core Abstraction. Define
Schema<T>. - Step 3: Primitive Validators. Create functions that return
Schema<string>, etc. - Step 4: Object/Array Validators. Recursive validation logic.
- Step 5: Type Inference. The
Infertype helper. - Step 6: Tree-shaking configuration. Ensure exports are split.
Refining the "Runtime Type Checking" implementation: I don't want to just write
if (typeof x === 'string'). I want to provide a builder pattern or functional primitives. Let's go with Functional Primitives for better tree-shaking.string()-> returnsSchema<string>object({ name: string() })-> returnsSchema<{ name: string }>
Handling Tree-shaking: If I export a class like
class Validator { ... }, methods usually stay unless specifically optimized. If I export small functions:export const string = () => ... export const number = () => ...This is the best for tree-shaking. If the user only imports
string,numberis never included.Let's write the code.
- File:
src/types.ts: Base interfaces. - File:
src/primitives.ts:string,number,boolean. - File:
src/composites.ts:object,array. - File:
src/index.ts: Aggregates exports.
Wait, I need to make sure the "Utility" part covers more than just validation. The prompt asks for a "Utility library". Validation is the "runtime type checking" part. I should add a few generic utility functions (like
pick,omit) that are also type-safe, to demonstrate the "library" aspect.Revised Plan:
- Configuration:
package.json(ESM, sideEffects: false),tsconfig.json. - Validation Module:
Resulttype for validation output.Schemainterface.- Implementations for
string,number,object,array. - Type inference helper.
- General Utility Module:
identity,pick,groupBy(examples of type-safe utils).
- Usage Example: A snippet showing how to use it.
Self-Correction during drafting: Writing a full validation library (like Zod) from scratch in a single response is too much code. I will implement a mini version (let's call it
LightCheck) that demonstrates the pattern perfectly. For Tree-shaking, I must emphasize theexportsfield inpackage.jsonand the module syntax.Drafting the Validation Logic:
export type Success<T> = { ok: true; value: T }; export type Failure = { ok: false; errors: string[] }; export type Result<T> = Success<T> | Failure; export interface Schema<T> { parse(input: unknown): Result<T>; }Drafting the Utilities:
pickis a classic hard TypeScript problem.export const pick = <T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> => ...Drafting the Package Config: Crucial for tree-shaking.
{ "type": "module", "sideEffects": false, "exports": { ".": "./dist/index.js", "./validate": "./dist/validate/index.js", "./utils": "./dist/utils/index.js" } }Final Polish: The user asked for "A TypeScript utility library". I will provide the file structure, the code, and the configuration. I will explain why it supports tree-shaking.
Let's stick to one coherent library name:
ts-lite.File Structure:
src/core/result.tssrc/validate/primitives.tssrc/validate/object.tssrc/utils/collection.tssrc/index.tspackage.jsontsconfig.json
I will keep the code concise but functional.
Wait,
Resulttype: Monadic parsing is cool.parse(input)returns either{ success: true, data: T }or{ success: false, error: ... }.Let's write it out. Here is a complete, lightweight TypeScript utility library designed for Runtime Type Checking with full Tree-Shaking support.
I call this library
ts-runtime-guard.Design Philosophy
- Runtime Safety: Uses a Schema-based approach (similar to Zod or io-ts) to validate unknown inputs at runtime.
- Compile-time Inference: Automatically infers TypeScript static types from the runtime schemas.
- Tree-Shaking: The code is split into small, pure functions. Modern bundlers (Webpack, Rollup, Vite) will only include the specific validators (e.g.,
string,object) that you actually import.
1. Project Configuration
package.jsonCritical settings for tree-shaking aresideEffects: falseand theexportsmap.{ "name": "ts-runtime-guard", "version": "1.0.0", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", "sideEffects": false, "exports": { ".": { "import": "./dist/index.js", "types": "./dist/index.d.ts" } }, "scripts": { "build": "tsc" }, "devDependencies": { "typescript": "^5.0.0" } }tsconfig.json{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "outDir": "./dist", "rootDir": "./src", "declaration": true, "strict": true, "moduleResolution": "node", "esModuleInterop": true }, "include": ["src"] }
2. The Source Code
We will organize the code so users can import granularly.
src/core/result.tsThe internal representation of a validation result.
// src/core/result.ts // We export success and failure helpers to keep logic pure export type Success<T> = { success: true; data: T }; export type Failure = { success: false; error: string }; export type Result<T> = Success<T> | Failure; export const ok = <T>(data: T): Success<T> => ({ success: true, data }); export const err = (message: string): Failure => ({ success: false, error: message });src/types.tsThe base interface for all validators.
// src/types.ts import { Result } from './core/result'; export interface Validator<T> { /** * Validates input at runtime. * Used for logic: if (res.success) { ... } */ check(input: unknown): Result<T>; /** * Type guard. * Used for narrowing: if (is(data)) { ... } */ is(input: unknown): input is T; }src/primitives.tsValidators for basic types. Note that each file is self-contained.
// src/primitives.ts import { Validator } from './types'; import { Result, ok, err } from './core/result'; // Abstract base class to reduce boilerplate for simple primitives abstract class PrimitiveValidator<T> implements Validator<T> { constructor(private typeName: string) {} check(input: unknown): Result<T> { if (typeof input === this.typeName) { return ok(input as T); } return err(`Expected ${this.typeName}, got ${typeof input}`); } is(input: unknown): input is T { return this.check(input).success; } } // Tree-shakable exports export const string = () => new (class extends PrimitiveValidator<string> {}('string')); export const number = () => new (class extends PrimitiveValidator<number> {}('number')); export const boolean = () => new (class extends PrimitiveValidator<boolean> {}('boolean'));src/composites.tsValidators for Objects and Arrays.
// src/composites.ts import { Validator } from './types'; import { Result, ok, err } from './core/result'; class ArrayValidator<T> implements Validator<T[]> { constructor(private itemValidator: Validator) {} check(input: unknown): Result<T[]> { if (!Array.isArray(input)) { return err(`Expected array, got ${typeof input}`); } const data: T[] = []; for (let i = 0; i < input.length; i++) { const result = this.itemValidator.check(input[i]); if (!result.success) { return err(`Index ${i}: ${result.error}`); } data.push(result.data); } return ok(data); } is(input: unknown): input is T[] { return this.check(input).success; } } class ObjectValidator<T extends Record<string, any>> implements Validator<T> { constructor(private shape: { [K in keyof T]: Validator }) {} check(input: unknown): Result<T> { if (typeof input !== 'object' || input === null) { return err(`Expected object, got ${typeof input}`); } const inputObj = input as Record<string, unknown>; const resultObj: any = {}; for (const key in this.shape) { // Ensure we own the property if (Object.prototype.hasOwnProperty.call(this.shape, key)) { const validator = this.shape[key]; const value = inputObj[key]; const result = validator.check(value); if (!result.success) { return err(`Property "${key}": ${result.error}`); } resultObj[key] = result.data; } } return ok(resultObj as T); } is(input: unknown): input is T { return this.check(input).success; } } // Factory functions export const array = <T>(itemValidator: Validator): Validator => new ArrayValidator(itemValidator); export const object = <T extends Record<string, any>>(shape: { [K in keyof T]: Validator }): Validator => new ObjectValidator(shape);src/inference.tsThe magic utility to extract static types.
// src/inference.ts import { Validator } from './types'; // This is the utility users use to get the TypeScript type export type Infer<V extends Validator<any>> = V extends Validator ? T : never;src/index.tsThe public entry point. We explicitly re-export to control what the user sees.
// src/index.ts // Core Types export type { Validator } from './types'; export type { Infer } from './inference'; // Primitives (Tree-shakable) export { string, number, boolean } from './primitives'; // Composites (Tree-shakable) export { array, object } from './composites'; // Utilities (Optional, demonstrating modular utils) export const utils = { capitalize: (str: string) => str.charAt(0).toUpperCase() + str.slice(1) };
3. How to use it (Usage Example)
Create a file
demo.ts:import { object, string, number, array, Infer } from './dist/index.js'; // 1. Define Runtime Schema const UserSchema = object({ id: number(), name: string(), tags: array(string()), role: string() // Assume role is optional for this example, or create an optional util }); // 2. Infer Static TypeScript Type type User = Infer<typeof UserSchema>; // Mock API Response (unknown input) const apiResponse: unknown = { id: 1, name: "Alice", tags: ["admin", "user"], role: "superuser" }; // 3. Validate at Runtime const result = UserSchema.check(apiResponse); if (result.success) { // Safe to use as User const user: User = result.data; console.log(`User Validated: ${user.name}`); } else { console.error("Validation Failed:", result.error); } // 4. Using Type Guards function greet(data: unknown) { if (UserSchema.is(data)) { // TypeScript knows 'data' is User here console.log(`Hello, ${data.name}`); } else { console.log("Not a user"); } }
4. Why this supports Tree-Shaking
- ES Modules: We used
export constandexport classin separate files. sideEffects: false: Inpackage.json, this tells the bundler that if a file isn't imported, it doesn't need to be included.- No Global Pollution: We do not attach validators to a global object (like
V.string()). Instead, we export individual functions (string()).
Scenario: If a user only imports
stringandnumber:import { string, number } from 'ts-runtime-guard';The bundler will analyze
src/index.ts, see thatarrayandobjectare never imported by the application code, and completely drop the code forObjectValidatorandArrayValidatorfrom the final production bundle.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.