createAssetValidator

See source code

Creates a validator for a specific asset record type. This factory function generates a complete validator that validates the entire asset record structure including the base properties (id, typeName, type, meta) and the type-specific props.

function createAssetValidator<
  Type extends string,
  Props extends JsonObject,
  Meta extends JsonObject = JsonObject,
>(
  type: Type,
  props?:
    | {
        [K in keyof Props]: T.Validatable<Props[K]>;
      }
    | T.Validator<Props>,
  meta?: {
    [K in keyof Meta]: T.Validatable<Meta[K]>;
  },
): T.ObjectValidator<
  import("@tldraw/utils").Expand<
    {
      [P in
        | "id"
        | "meta"
        | "typeName"
        | (undefined extends Props ? never : "props")
        | (undefined extends Type ? never : "type")]: TLBaseAsset<
        Type,
        Props
      >[P];
    } & {
      [P in
        | (undefined extends Props ? "props" : never)
        | (undefined extends Type ? "type" : never)]?:
        | TLBaseAsset<Type, Props>[P]
        | undefined;
    }
  >
>;

Example

import { createAssetValidator, TLBaseAsset } from "@tldraw/tlschema";
import { T } from "@tldraw/validate";

// Define a custom asset type
type TLCustomAsset = TLBaseAsset<
  "custom",
  {
    url: string;
    title: string;
    description?: string;
  }
>;

// Create validator using a per-key record (recommended)
const customAssetValidator = createAssetValidator("custom", {
  url: T.string,
  title: T.string,
  description: T.string.optional(),
});

// Or using a T.object validator
const customAssetValidator2 = createAssetValidator(
  "custom",
  T.object({
    url: T.string,
    title: T.string,
    description: T.string.optional(),
  }),
);

Parameters

NameDescription

type

Type;

The asset type identifier (e.g., 'image', 'video', 'bookmark')

props

  | {
      [K in keyof Props]: T.Validatable<Props[K]>;
    }
  | T.Validator<Props>;

A validator or per-key validator record for the asset's type-specific properties

meta

{
  [K in keyof Meta]: T.Validatable<Meta[K]>;
};

An optional per-key validator record for the asset's meta properties

Returns

T.ObjectValidator<
  import("@tldraw/utils").Expand<
    {
      [P in
        | "id"
        | "meta"
        | "typeName"
        | (undefined extends Props ? never : "props")
        | (undefined extends Type ? never : "type")]: TLBaseAsset<
        Type,
        Props
      >[P];
    } & {
      [P in
        | (undefined extends Props ? "props" : never)
        | (undefined extends Type ? "type" : never)]?:
        | TLBaseAsset<Type, Props>[P]
        | undefined;
    }
  >
>;

A complete validator for the asset record type

Prev
createAssetPropsMigrationSequence
Next
createBindingId