Libraries
    Preparing search index...

    Function parseString

    • Creates a parse-string schema that validates a string against a template pattern and parses it into a strongly-typed object.

      The first argument defines the result shape via object(...), and the second argument is a callback receiving a typed $template tagged-template function whose template expressions are type-safe property selectors.

      Type Parameters

      Parameters

      • objectSchema: TSchema

        An ObjectSchemaBuilder defining the result type and per-property validation schemas.

      • templateBuilder: ($template: ParseStringTemplateTag<TSchema>) => ParseStringTemplateDefinition

        Callback receiving the typed $template tagged-template function. Must return the result of invoking $template.

      Returns ParseStringSchemaBuilder<InferType<TSchema>>

      A ParseStringSchemaBuilder whose validate() accepts a string and whose InferType is the object schema's inferred type.

      const RouteSchema = parseString(
      object({
      userId: string().uuid(),
      id: number()
      }),
      $t => $t`/orders/${t => t.id}/${t => t.userId}`
      );

      const result = RouteSchema.validate('/orders/42/550e8400-e29b-41d4-a716-446655440000');
      // result.valid === true
      // result.object === { id: 42, userId: '550e8400-e29b-41d4-a716-446655440000' }

      type Route = InferType<typeof RouteSchema>;
      // { id: number; userId: string }
      const schema = parseString(
      object({
      order: object({ id: number() }),
      user: object({ name: string() })
      }),
      $t => $t`/orders/${t => t.order.id}/by/${t => t.user.name}`
      );