TypeScript Codegen
Esta página aún no está disponible en tu idioma.
yrest types reads your db.yml and writes a TypeScript interface for every collection. Use the generated types in your frontend code, in handler functions and with server.collection<T>() in tests, so they all agree with the mock data.
Generating the types
Section titled “Generating the types”yrest types db.yml # prints to stdoutyrest types db.yml --output db.types.ts # writes a fileyrest types db.yml --output db.types.ts --watch # regenerates on every changeGiven this db.yml:
_schema: users: email: _required: true _format: email role: _enum: [admin, editor]_rel: posts: userId: usersusers: - id: 1 name: Ana email: ana@test.com role: admin - id: 2 name: Luis address: { city: Lima }posts: - id: 1 title: Hello userId: 1yrest types db.yml prints:
// Auto-generated by yrest types — do not edit manually.// Source: db.yml
/** Item of the `users` collection. */export interface User { id: number; name: string; /** * @format email */ email: string; role?: "admin" | "editor"; address?: { city: string };}
/** Item of the `posts` collection. */export interface Post { id: number; title: string; /** FK → users.id */ userId: number;}
/** Union of all collection names in the source file. */export type CollectionName = "users" | "posts";
/** Maps each collection name to its item array type. */export interface Collections { users: User[]; posts: Post[];}Interface names
Section titled “Interface names”Each collection becomes an interface named in singular PascalCase:
| Collection | Interface |
|---|---|
users | User |
categories | Category |
addresses | Address |
post_tags | PostTag |
order-items | OrderItem |
If two collections would get the same name (user and users), the second one keeps its plural form.
Inferred types
Section titled “Inferred types”Types are inferred from every item of the collection, not a sample:
- A field present on all items is required; a field missing on any item is optional (
?). - Different types across items become a union:
1and"one"givenumber | string. nullvalues add| null. A field that is only evernullisunknown.- Nested objects are merged into one inline shape, so a key missing in some of them is optional.
- Array elements are pooled:
[{ k: "a" }, { v: 2 }]gives{ k?: string; v?: number }[]. An empty array isunknown[]. - Keys that are not valid identifiers are quoted (
"unit-price": number). - An empty collection gets an index signature (
[key: string]: unknown).
_schema overrides
Section titled “_schema overrides”Declarations in _schema take priority over the data:
_schema key | Effect on the generated field |
|---|---|
_type | Sets the type (integer and number → number) |
_required: true | Required, even if some items lack the field |
_required: false | Optional, even if every item has the field |
required / optional | Shorthand for the two above |
_enum | Literal union: "admin" | "editor" |
_nullable: true | Adds | null |
_items | Element type of an array field (_type or _enum) |
_description | JSDoc text |
_format | @format JSDoc tag |
_deprecated: true | @deprecated JSDoc tag |
A field declared in _schema but absent from the data is still included, as optional unless _required: true. Without a _type it is unknown.
Relations
Section titled “Relations”many2one and one2one foreign keys declared in _rel are annotated with the collection they point to, including the @foreignKey form of the DSL:
/** FK → users.id */userId: number;Directives are not resolved
Section titled “Directives are not resolved”yrest types only reads the file. __uuid_gen / __fk directives are not resolved and db.yml is never rewritten — fields that hold a directive are typed string, which is what they become once the server resolves them.
Using the types
Section titled “Using the types”In a test, with the programmatic API:
import { createYrestServer } from "@yrest/cli";import type { User } from "./db.types";
const server = createYrestServer({ file: "./db.yml", port: 0 });await server.start();server.collection<User>("users").create({ name: "Eva", email: "eva@test.com" });In a handler:
import { defineHandler } from "@yrest/cli";import type { User } from "./db.types";
export const admins = defineHandler((req, { collection }) => ({ body: collection<User>("users").findWhere((u) => u.role === "admin"),}));Collections maps every collection name to its array type, for helpers that work with any collection:
import type { Collections, CollectionName } from "./db.types";
async function fetchAll<K extends CollectionName>(name: K): Promise<Collections[K]> { const res = await fetch(`http://localhost:3070/${name}`); return res.json();}Programmatic use
Section titled “Programmatic use”The generator is exported as generateTypes, a pure function that returns the source text:
import { generateTypes } from "@yrest/cli";
const source = generateTypes({ data: { users: [{ id: 1, name: "Ana" }] },});It also takes the parsed schema and relations, and a source option for the header comment.
Reference
Section titled “Reference”| Flag | Short | Default | Description |
|---|---|---|---|
--output | -o | (stdout) | Write to a file instead of printing to stdout |
--watch | -w | false | Regenerate on every change of the source file (needs --output) |
--watch polls the file, like yrest serve --watch, so it keeps working with editors that save by replacing the file.
Next steps
Section titled “Next steps”- Handler Functions — use the types in
defineHandler - Programmatic API — typed
server.collection<T>()in tests - Schema — refine the generated types with
_schema - CLI Reference — every
yrestcommand