createShapeValidator

See source code

Creates a validator for a specific shape type.

This function generates a complete validator that can validate shape records of the specified type, including both the base shape properties and any custom properties and metadata specific to that shape type.

function createShapeValidator<
  Type extends string,
  Props extends JsonObject,
  Meta extends JsonObject,
>(
  type: Type,
  props?: {
    [K in keyof Props]: T.Validatable<Props[K]>
  },
  meta?: {
    [K in keyof Meta]: T.Validatable<Meta[K]>
  }
): T.ObjectValidator<
  import('@tldraw/utils').Expand<
    {
      [P in
        | 'id'
        | 'index'
        | 'isLocked'
        | 'meta'
        | 'opacity'
        | 'parentId'
        | 'rotation'
        | 'typeName'
        | 'x'
        | 'y'
        | (undefined extends Props ? never : 'props')
        | (undefined extends Type ? never : 'type')]: TLBaseShape<
        Type,
        Props
      >[P]
    } & {
      [P_1 in
        | (undefined extends Props ? 'props' : never)
        | (undefined extends Type ? 'type' : never)]?:
        | TLBaseShape<Type, Props>[P_1]
        | undefined
    }
  >
>

Example

// Create a validator for a custom shape type
const customShapeValidator = createShapeValidator('custom', {
  width: T.number,
  height: T.number,
  color: T.string,
})

// Use the validator to validate shape data
const shapeData = {
  id: 'shape:abc123',
  typeName: 'shape',
  type: 'custom',
  x: 100,
  y: 200,
  // ... other base properties
  props: {
    width: 150,
    height: 100,
    color: 'red',
  },
}

const validatedShape = customShapeValidator.validate(shapeData)

Parameters

NameDescription

type

Type

The string literal type for this shape (e.g., 'geo', 'arrow')

props

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

Optional validator configuration for shape-specific properties

meta

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

Optional validator configuration for shape-specific metadata

Returns

T.ObjectValidator<
  import('@tldraw/utils').Expand<
    {
      [P in
        | 'id'
        | 'index'
        | 'isLocked'
        | 'meta'
        | 'opacity'
        | 'parentId'
        | 'rotation'
        | 'typeName'
        | 'x'
        | 'y'
        | (undefined extends Props ? never : 'props')
        | (undefined extends Type ? never : 'type')]: TLBaseShape<
        Type,
        Props
      >[P]
    } & {
      [P_1 in
        | (undefined extends Props ? 'props' : never)
        | (undefined extends Type ? 'type' : never)]?:
        | TLBaseShape<Type, Props>[P_1]
        | undefined
    }
  >
>

A validator that can validate complete shape records of the specified type

Prev
createShapePropsMigrationSequence
Next
createTLSchema