App Developer Guide
You want to use typesugar features directly in your application or library. This guide walks you through installation, configuration, and your first macros.
Quick Setup
Run the setup wizard:
npx typesugar initSelect "I want to use typesugar in my app/library" when prompted. This installs everything you need and creates an example file.
Manual Setup
Step 1: Install Packages
Install the core transformer and the macro packages you want to use:
# Core (required)
npm install --save-dev @typesugar/transformer ts-patch
# Popular macro packages (install what you need)
npm install @typesugar/derive # Auto-derive implementations
npm install @typesugar/reflect # Type reflection
npm install @typesugar/sql # Type-safe SQLOr install the umbrella package that includes everything:
npm install typesugar
npm install --save-dev ts-patchStep 2: Configure tsconfig.json
Add the transformer plugin:
{
"compilerOptions": {
"plugins": [
{ "name": "typesugar/language-service" },
{ "transform": "@typesugar/transformer", "type": "program" }
]
}
}The language-service plugin provides IDE support (optional but recommended).
Step 3: Install ts-patch
npx ts-patch installAdd to your prepare script:
{
"scripts": {
"prepare": "ts-patch install -s"
}
}Step 4: Configure Your Bundler
If you use Vite, Webpack, esbuild, or another bundler:
npm install --save-dev unplugin-typesugarVite:
// vite.config.ts
import { defineConfig } from "vite";
import typesugar from "unplugin-typesugar/vite";
export default defineConfig({
plugins: [typesugar()],
});See environment-specific guides for other bundlers.
Your First Macros
Compile-Time Evaluation
comptime() runs code at build time and inlines the result:
import { comptime } from "typesugar";
// This runs at compile time, not runtime
const BUILD_TIME = comptime(new Date().toISOString());
const COMPUTED = comptime(() => {
let sum = 0;
for (let i = 1; i <= 100; i++) sum += i;
return sum;
});
console.log(`Built at: ${BUILD_TIME}`); // "Built at: 2024-01-15T10:30:00.000Z"
console.log(`Sum: ${COMPUTED}`); // "Sum: 5050"After compilation:
const BUILD_TIME = "2024-01-15T10:30:00.000Z";
const COMPUTED = 5050;Derive Macros
@derive() auto-generates common implementations:
import { derive, Eq, Clone, Debug, Json } from "@typesugar/derive";
@derive(Eq, Clone, Debug, Json)
class User {
constructor(
public id: number,
public name: string,
public email: string
) {}
}
const user = new User(1, "Alice", "alice@example.com");
// Auto-generated methods:
user.equals(user.clone()); // true
user.debug(); // "User { id: 1, name: \"Alice\", email: \"alice@example.com\" }"
user.toJson(); // "{\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\"}"
User.fromJson("..."); // Parse JSON back to UserAvailable derives: Eq, Ord, Clone, Debug, Hash, Default, Json, Builder, TypeGuard
Type-Safe SQL
The sql tagged template creates parameterized queries:
import { sql } from "@typesugar/sql";
const userId = 42;
const status = "active";
const query = sql`
SELECT * FROM users
WHERE id = ${userId} AND status = ${status}
`;
console.log(query.text); // "SELECT * FROM users WHERE id = $1 AND status = $2"
console.log(query.params); // [42, "active"]Type Reflection
Get type information at compile time:
import { typeInfo, fieldNames, validator } from "@typesugar/reflect";
interface User {
id: number;
name: string;
email: string;
}
const fields = fieldNames<User>(); // ["id", "name", "email"]
const validate = validator<User>(); // Runtime type guard
if (validate(unknownData)) {
// unknownData is now typed as User
}See Macro Expansion
To see what your macros expand to:
npx typesugar expand src/main.tsOr with a diff:
npx typesugar expand src/main.ts --diffVerify Setup
Run diagnostics:
npx typesugar doctorPackage Reference
| Package | Features |
|---|---|
typesugar | comptime(), derive, reflect, operators, etc. (umbrella package) |
@typesugar/derive | @derive(), Eq, Ord, Clone, Debug, Hash, Default, Json, Builder, TypeGuard |
@typesugar/reflect | typeInfo<T>(), fieldNames<T>(), validator<T>(), @reflect |
@typesugar/sql | sql tagged template |
@typesugar/typeclass | @typeclass, @instance, @derive, summon<T>() |
@typesugar/contracts | requires:, ensures:, invariant: |
@typesugar/std | match() (fluent pattern matching), extension methods |
@typesugar/fp | Option, Result, IO |
@typesugar/strings | regex, html, raw tagged templates |
@typesugar/units | units tagged template for dimensional analysis |
