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>(
  type: Type,
  props: T.Validator<Props>,
): T.ObjectValidator<
  import("@tldraw/utils").Expand<
    {
      [P in
        | "id"
        | "meta"
        | "typeName"
        | (undefined extends Props ? never : "props")
        | (undefined extends Type ? never : "type")]: {
        id: TLAssetId;
        meta: JsonObject;
        props: Props;
        type: Type;
        typeName: "asset";
      }[P];
    } & {
      [P in
        | (undefined extends Props ? "props" : never)
        | (undefined extends Type ? "type" : never)]?:
        | {
            id: TLAssetId;
            meta: JsonObject;
            props: Props;
            type: Type;
            typeName: "asset";
          }[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 for the custom asset
const customAssetValidator = createAssetValidator(
  "custom",
  T.object({
    url: T.string,
    title: T.string,
    description: T.string.optional(),
  }),
);

// Use the validator
const assetData = {
  id: "asset:custom123",
  typeName: "asset" as const,
  type: "custom" as const,
  props: {
    url: "https://example.com",
    title: "My Custom Asset",
  },
  meta: {},
};

const validatedAsset = customAssetValidator.validate(assetData);

Parameters

NameDescription

type

Type;

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

props

T.Validator<Props>;

The validator for the asset's type-specific properties

Returns

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

A complete validator for the asset record type

Prev
compressLegacySegments
Next
createBindingId