Designing TypeScript Utility Library
The user is asking me to help design a TypeScript utility library with runtime type checking and support for tree-shaking. I need to consider project structure, configurations like tsconfig, and bundling with tools like rollup or esbuild. They’re looking for runtime type checks possibly using zod or custom validators, aiming for a general-purpose library or type utilities. I'll suggest functions like isString and provide a clear folder structure and implementation steps, ensuring I keep it concise yet informative.Creating a Utility Library Design
The user wants to create a TypeScript utility library with minimal dependencies for flexibility. Ensuring tree-shaking is essential, so I’ll use ESM, individually exported functions, and set sideEffects: false to avoid issues with top-level side effects. I might also consider supporting both Deno and Node.
My design will include setup instructions: a package.json configured as a module with an exports map, a suitable tsconfig, and either a tsup or tsc bundler setup to generate ESM-compatible code.Setting Up tsup Config and Type-Checking Utilities
I can showcase a basic tsup.config.ts to define the build configuration, using features like ESM and CJS formats, source maps, and tree-shaking enabled.
Regarding runtime type-checking utilities, I’ll implement type predicates such as isString, isNumber, and a tiny schema builder. This would include defining a Validator type and functions for object validation using generics.
I’ll also set up assert functions to ensure values conform to specified validators, enhancing type safety throughout the library.Outlining the TypeScript Utility Library
The user wants me to create a TypeScript utility library focused on runtime type checking and tree-shaking support. I will name the library @your-scope/rtk-utils.
I’ll provide a step-by-step guide that outlines initializing the project, including commands like npm init, and setting up configuration files such as package.json, tsconfig.json, and tsup.config.ts.
The utility code will be shared along with usage examples to demonstrate tree-shaking, showing how to import specific utilities while ensuring the bundler drops unused code. However, they haven't specified if they want any command execution details.Delivering TypeScript Utility Library Structure
I’ll create a specific file structure for the TypeScript utility library, focusing on enabling tree-shaking through strategies like using pure functions, ESM exports, and setting sideEffects: false.
My package.json will include necessary fields and types, while the tsup.config.ts outlines the build settings. The tsconfig.json ensures proper TypeScript configurations without emitting files directly since tsup handles the compiling.
Under /src, I’ll implement the validators, starting with basic types and combinators, ensuring type safety while avoiding large polyfills. The library will also include utility functions like assertType and parseType for runtime checks. Finally, I’ll show an example of how to import and use the library effectively.Structuring TypeScript Utility Library
I’ll emphasize tree-shaking by ensuring each file exports individually, allowing the bundler to eliminate unimported code. My folder structure will include src/index.ts and a runtime folder with core.ts, primitives.ts, combinators.ts, and assert.ts.
For core.ts, I’ll define the Validator and TypeOf types. In primitives.ts, I will create validators such as string, number, and boolean, while ensuring named exports avoid conflicts with TypeScript keywords. Combinators will handle arrays, objects, unions, and more. Finally, I'll ensure that the library provides a complete runtime type-checking experience.Implementing TypeScript Runtime Library
In the /src/runtime/assert.ts, I'll define an assertType function to validate types. It will throw a TypeError if the value doesn't match the expected type. Additionally, I'll implement parseType, which also throws an error but returns the validated value.
I'll set up safeParseType to return an object with success status and any errors, although it’s optional. For the index file, I’ll re-export everything, maintaining tree-shaking support with named exports and setting sideEffects in the package.json. The final example will showcase usage, demonstrating effective tree-shaking. Below is a minimal, ready-to-use TypeScript utility library that:
- Provides runtime type checking with good type inference
- Is tree-shakable (ESM output,
sideEffects: false, pure named exports)
You can copy these files into a new project and run npm install + npm run build.
1. Project structure
your-lib/
package.json
tsconfig.json
tsup.config.ts
src/
index.ts
runtime/
core.ts
primitives.ts
combinators.ts
assert.ts
2. Configuration files
package.json
{
"name": "@example/typed-utils",
"version": "0.1.0",
"description": "Tiny runtime type-checking utilities with TypeScript inference and tree-shaking",
"license": "MIT",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"sideEffects": false,
"scripts": {
"build": "tsup",
"clean": "rm -rf dist"
},
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.6.0"
}
}
Key for tree-shaking:
"type": "module" and "module": "./dist/index.mjs" → ESM build
"sideEffects": false → bundlers can safely drop unused exports
- Named exports only (no side-effectful code)
tsconfig.json
{
"compilerOptions": {
"target": "ES2019",
"module": "ESNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"isolatedModules": true,
"declaration": true,
"noEmit": true
},
"include": ["src"]
}
noEmit: true is fine because tsup does the build.
tsup.config.ts
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts'],
outDir: 'dist',
format: ['esm', 'cjs'],
dts: true,
sourcemap: true,
clean: true,
treeshake: true,
splitting: false,
minify: false
});
treeshake: true ensures the built bundle is optimized.
3. Runtime type utilities
src/runtime/core.ts
export type Validator<T> = (value: unknown) => value is T;
/**
* Given a Validator, infer the TypeScript type it validates.
*/
export type TypeOf<V> = V extends Validator<infer T> ? T : never;
src/runtime/primitives.ts
import type { Validator } from './core';
export const string: Validator<string> = (v: unknown): v is string =>
typeof v === 'string';
export const number: Validator<number> = (v: unknown): v is number =>
typeof v === 'number' && !Number.isNaN(v);
export const boolean: Validator<boolean> = (v: unknown): v is boolean =>
typeof v === 'boolean';
export const bigint: Validator<bigint> = (v: unknown): v is bigint =>
typeof v === 'bigint';
export const symbol: Validator<symbol> = (v: unknown): v is symbol =>
typeof v === 'symbol';
export const date: Validator<Date> = (v: unknown): v is Date =>
v instanceof Date && !Number.isNaN(v.getTime());
export const unknownValue: Validator<unknown> = (_: unknown): _ is unknown =>
true;
export const anyValue: Validator<any> = (_: unknown): _ is any => true;
export const neverValue: Validator<never> = (_: unknown): _ is never => false;
src/runtime/combinators.ts
import type { Validator, TypeOf } from './core';
/**
* Optional: value can be T or undefined.
*/
export function optional<T>(validator: Validator<T>): Validator<T | undefined> {
return (value: unknown): value is T | undefined =>
value === undefined || validator(value);
}
/**
* Nullable: value can be T or null.
*/
export function nullable<T>(validator: Validator<T>): Validator<T | null> {
return (value: unknown): value is T | null =>
value === null || validator(value);
}
/**
* Array of T.
*/
export function arrayOf<T>(validator: Validator<T>): Validator<T[]> {
return (value: unknown): value is T[] =>
Array.isArray(value) && value.every(validator);
}
/**
* Literal value (string | number | boolean | null).
*/
export function literal<T extends string | number | boolean | null>(
expected: T
): Validator<T> {
return (value: unknown): value is T => value === expected;
}
/**
* Union of validators: T1 | T2 | ...
*/
export function union<V extends Validator<any>[]>(
...validators: V
): Validator<TypeOf<V[number]>> {
return (value: unknown): value is TypeOf<V[number]> =>
validators.some((v) => v(value));
}
/**
* Object shape.
*
* Example:
* const User = object({
* id: string,
* age: optional(number),
* });
*/
export type Shape = Record<string, Validator<any>>;
export type InferShape<S extends Shape> = {
[K in keyof S]: TypeOf<S[K]>;
};
export function object<S extends Shape>(shape: S): Validator<InferShape<S>> {
return (value: unknown): value is InferShape<S> => {
if (typeof value !== 'object' || value === null) return false;
const obj = value as Record<string, unknown>;
for (const key in shape) {
const validate = shape[key];
const propValue = obj[key];
if (!validate(propValue)) {
return false;
}
}
return true;
};
}
/**
* Record<string, T>.
*/
export function recordOf<T>(
valueValidator: Validator<T>
): Validator<Record<string, T>> {
return (value: unknown): value is Record<string, T> => {
if (typeof value !== 'object' || value === null) return false;
for (const key in value as Record<string, unknown>) {
if (!valueValidator((value as Record<string, unknown>)[key])) {
return false;
}
}
return true;
};
}
src/runtime/assert.ts
import type { Validator } from './core';
/**
* Assert that a value matches a validator.
* Throws TypeError on failure.
*/
export function assertType<T>(
validator: Validator<T>,
value: unknown,
message?: string
): asserts value is T {
if (!validator(value)) {
throw new TypeError(message ?? 'Value did not match the expected type');
}
}
/**
* Parse a value with a validator.
* Returns typed value or throws TypeError.
*/
export function parseType<T>(
validator: Validator<T>,
value: unknown,
message?: string
): T {
if (!validator(value)) {
throw new TypeError(message ?? 'Value did not match the expected type');
}
return value as T;
}
/**
* Safe parse: returns a discriminated union instead of throwing.
*/
export function safeParseType<T>(
validator: Validator<T>,
value: unknown
): { success: true; data: T } | { success: false; error: string } {
if (validator(value)) {
return { success: true, data: value as T };
}
return { success: false, error: 'Value did not match the expected type' };
}
src/index.ts
// Core types
export type { Validator, TypeOf } from './runtime/core';
// Primitives
export {
string,
number,
boolean,
bigint,
symbol,
date,
unknownValue,
anyValue,
neverValue
} from './runtime/primitives';
// Combinators
export {
optional,
nullable,
arrayOf,
literal,
union,
object,
type Shape,
type InferShape,
recordOf
} from './runtime/combinators';
// Assertions / parsing
export { assertType, parseType, safeParseType } from './runtime/assert';
4. Usage examples
Basic runtime type checking
import {
string,
number,
optional,
object,
TypeOf,
assertType,
parseType
} from '@example/typed-utils';
const UserValidator = object({
id: string,
name: string,
age: optional(number)
});
type User = TypeOf<typeof UserValidator>;
function handleIncoming(data: unknown) {
assertType(UserValidator, data); // throws if invalid
// From here on, `data` is a fully-typed `User`
data.id.toUpperCase();
console.log(data.age ?? 'unknown');
}
const raw = JSON.parse('{"id": "123", "name": "Alice"}');
const user = parseType(UserValidator, raw); // user: User
Tree-shaking in consumers
If a consumer only imports string:
// In consuming app:
import { string } from '@example/typed-utils';
if (string(someValue)) {
// ...
}
Bundlers like Webpack/Rollup/Vite will:
- Only include the code for
string (and whatever it depends on)
- Drop everything else (
object, recordOf, etc.) because:
- The library is ESM
- The exports are named
sideEffects: false is set
- Functions have no side effects at module load time
5. Build
From the project root:
npm install
npm run build
This will output dist/index.mjs, dist/index.cjs, and dist/index.d.ts, ready to publish or use locally (e.g. via npm link or pnpm link).
If you want, I can extend this with more combinators (e.g. tuples, intersections, branded types) or add tests and example usage with a bundler to verify tree-shaking.