Aller au contenu

TypeScript Codegen

Ce contenu n’est pas encore disponible dans votre langue.

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.

Terminal window
yrest types db.yml # prints to stdout
yrest types db.yml --output db.types.ts # writes a file
yrest types db.yml --output db.types.ts --watch # regenerates on every change

Given this db.yml:

_schema:
users:
email:
_required: true
_format: email
role:
_enum: [admin, editor]
_rel:
posts:
userId: users
users:
- id: 1
name: Ana
email: ana@test.com
role: admin
- id: 2
name: Luis
address: { city: Lima }
posts:
- id: 1
title: Hello
userId: 1

yrest 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[];
}

Each collection becomes an interface named in singular PascalCase:

CollectionInterface
usersUser
categoriesCategory
addressesAddress
post_tagsPostTag
order-itemsOrderItem

If two collections would get the same name (user and users), the second one keeps its plural form.

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: 1 and "one" give number | string.
  • null values add | null. A field that is only ever null is unknown.
  • 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 is unknown[].
  • Keys that are not valid identifiers are quoted ("unit-price": number).
  • An empty collection gets an index signature ([key: string]: unknown).

Declarations in _schema take priority over the data:

_schema keyEffect on the generated field
_typeSets the type (integer and number → number)
_required: trueRequired, even if some items lack the field
_required: falseOptional, even if every item has the field
required / optionalShorthand for the two above
_enumLiteral union: "admin" | "editor"
_nullable: trueAdds | null
_itemsElement type of an array field (_type or _enum)
_descriptionJSDoc 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.

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;

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.

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();
}

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.

FlagShortDefaultDescription
--output-o(stdout)Write to a file instead of printing to stdout
--watch-wfalseRegenerate 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.