---
title: Custom types
description: "Define an attribute type for a value the built-in types don’t hold, such as money."
seo:
  description: "Define a custom Active Record attribute type, such as money in cents or a list of sizes, stored in its column as a built-in type, and use it on any Model."
---

## At a glance

| To                                     | Write                                                               |
| -------------------------------------- | ------------------------------------------------------------------- |
| define a type stored as a built-in one | `defineType({ storedAs: "integer", cast, serialize, deserialize })` |
| give a generated attribute the type    | `static override attributes = { priceCents: money } as const`       |
| refuse a value                         | throw from `cast`                                                   |
| query by the type’s values             | `Product.where({ priceCents: new Money(500) })`                     |

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates, with the types in `src/types/`:

```ts product.ts
import { money } from "../types/money";
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    priceCents: money,
  } as const;
}
```

```ts shirt.ts
import { sizes } from "../types/sizes";
import { ApplicationRecord } from "./application-record";

export class Shirt extends ApplicationRecord {
  static override attributes = {
    sizes: { type: sizes, default: () => [] },
  } as const;
}
```

```ts money.ts
import { defineType } from "@forestfuture/active-record";

export class Money {
  readonly cents: number;

  constructor(cents: number) {
    this.cents = cents;
  }

  toString() {
    return `$${(this.cents / 100).toFixed(2)}`;
  }
}

export const money = defineType({
  storedAs: "integer",
  cast(input) {
    if (input instanceof Money) return input;
    if (Number.isSafeInteger(input)) return new Money(input as number);
    throw new TypeError("money is a Money or a whole number of cents");
  },
  serialize: (value) => value.cents,
  deserialize: (cents) => new Money(cents),
});
```

```ts sizes.ts
import { defineType } from "@forestfuture/active-record";

export const sizes = defineType({
  storedAs: "string",
  cast(input) {
    if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
      return input as string[];
    }
    throw new TypeError("sizes are a list of strings");
  },
  serialize: (list) => list.join(","),
  deserialize: (text) => (text === "" ? [] : text.split(",")),
});
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: b517af0d5b2a

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  priceCents: { type: "integer", null: false },
} as const;

/** shirts — last changed by 0001_create_tables.sql */
export const shirts = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  sizes: { type: "string", null: false, default: () => "" },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    products: { attributes: products, primaryKey: "id" },
    shirts: { attributes: shirts, primaryKey: "id" },
  },
  models: { Product: "products", Shirt: "shirts" },
});

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}

declare module "../models/shirt" {
  interface Shirt extends TableAttributes<typeof shirts, (typeof Shirt)["attributes"]> {}
}
```

```sql D1
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
CREATE TABLE shirts (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  sizes TEXT NOT NULL DEFAULT ''
);
```

```sql Postgres
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
CREATE TABLE shirts (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  sizes TEXT NOT NULL DEFAULT ''
);
```

## Defining a type

Define a type with `defineType`, naming the built-in type it’s stored as. This one keeps money as whole cents in an integer column:

```ts
import { defineType } from "@forestfuture/active-record";

export class Money {
  readonly cents: number;

  constructor(cents: number) {
    this.cents = cents;
  }

  toString() {
    return `$${(this.cents / 100).toFixed(2)}`;
  }
}

export const money = defineType({
  storedAs: "integer",
  cast(input) {
    if (input instanceof Money) return input;
    if (Number.isSafeInteger(input)) return new Money(input as number);
    throw new TypeError("money is a Money or a whole number of cents");
  },
  serialize: (value) => value.cents,
  deserialize: (cents) => new Money(cents),
});
```

A type has three functions:

| Function      | Takes                              | Returns                            |
| ------------- | ---------------------------------- | ---------------------------------- |
| `cast`        | a value given to the attribute     | the type’s value, or throws        |
| `serialize`   | the type’s value                   | a value of the type it’s stored as |
| `deserialize` | a value of the type it’s stored as | the type’s value                   |

The attribute’s TypeScript type is what `cast` returns, so `Money` here.

:::note
None of them is called with `null`, which is always NULL.
:::

## Using a type

Give the type to a generated attribute in `static attributes`, as `Product` does:

```ts
import { money } from "../types/money";
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    priceCents: money,
  } as const;
}
```

Changing an attribute’s type drops its generated default, as any [override](/models#overriding-attributes) of a type does. Give it a `default` if it needs one.

A Model that declares its attributes itself, with `Model.define`, takes the type in place of a type’s name: `total: { type: money, null: false }`.

## Refusing values

Throw from `cast` for a value the type can’t hold. Assigning or permitting that value then throws a `TypeError` naming the Model and attribute, with your error as its `cause`:

```ts
import { Product } from "./models/product";

Product.permit({ priceCents: "abc" }, "priceCents");
// TypeError: Product: "abc" isn't a valid value for "priceCents"
```

The same happens when `deserialize` throws for a stored value, and when `serialize` returns a value its stored type can’t hold. For a [filtered attribute](/serialization#filtering-attributes), the error has no `cause`, since yours may show the value.

## Querying by a type

Conditions take the type’s values, and anything `cast` takes:

```ts
import { gte } from "@forestfuture/active-record";
import { Product } from "./models/product";
import { Money } from "./types/money";

const cheap = await Product.where({ priceCents: new Money(500) }).toArray();
const pricey = await Product.where({ priceCents: gte(new Money(10_000)) })
  .order({ priceCents: "desc" })
  .toArray();
```

Values compare and sort as their stored values do, so money sorts by cents. A value `cast` throws for matches nothing.

## Changing values in place

A type can hold a value you change in place. This one keeps a list of sizes as text, and `Shirt` gives it to `sizes`:

```ts
import { defineType } from "@forestfuture/active-record";

export const sizes = defineType({
  storedAs: "string",
  cast(input) {
    if (Array.isArray(input) && input.every((size) => typeof size === "string")) {
      return input as string[];
    }
    throw new TypeError("sizes are a list of strings");
  },
  serialize: (list) => list.join(","),
  deserialize: (text) => (text === "" ? [] : text.split(",")),
});
```

Changes are found by comparing what `serialize` returns, so a size pushed onto the list is a change, and `save()` writes it:

```ts
import { Shirt } from "./models/shirt";

const shirt = await Shirt.findByOrThrow({ name: "Oxford" }); // sizes: ["S", "M"]
shirt.sizes.push("XL");
console.log(shirt.isChanged()); // true
await shirt.save(); // writes "S,M,XL"
```

An equal value in another object, such as a new `Money` of the same cents, isn’t a change.

> **Compared with Rails**
>
> Rails registers a type by name, with `ActiveRecord::Type.register(:money, MoneyType)`, and a Model writes `attribute :price, :money`. Here you pass the type itself, so TypeScript knows the attribute’s type. Rails’ types read the database’s values directly. Here a type is always stored as a built-in type, which reads and compares its values the same way on every database.
