ts-fortress
    Preparing search index...

    Function optional

    • Converts a Type to an optional property type.

      Type Parameters

      • T extends Readonly<
            {
                assertIs: (a: unknown) => asserts a is unknown;
                cast: (a: unknown) => unknown;
                defaultValue: unknown;
                fill: (a: unknown) => unknown;
                is: (a: unknown) => a is unknown;
                typeName: string;
                validate: (
                    a: unknown,
                ) => Result<
                    unknown,
                    readonly Readonly<
                        {
                            actualValue: unknown;
                            details?: ValidationErrorDetails;
                            expectedType: string;
                            path: readonly string[];
                            typeName: string;
                        },
                    >[],
                >;
            },
        >

        The Type to make optional

      Parameters

      • t: T

        The Type to make optional

      • Optionaloptions: Partial<Readonly<{ forceUndefinedDefault: boolean }>>

        Optional configuration

        • forceUndefinedDefault

          If true, forces defaultValue to be undefined. Use this for recursive types to avoid infinite loops.

      Returns OptionalPropertyType<T>

      An OptionalPropertyType that can be used in record definitions

      import * as t from 'ts-fortress';

      type EvenNumber = Readonly<{ type: 'even'; next?: OddNumber }>;

      type OddNumber = Readonly<{ type: 'odd'; next?: EvenNumber }>;

      // When using optional fields in mutually recursive types,
      // use forceUndefinedDefault to avoid infinite loops when accessing defaultValue
      const EvenNumber: t.Type<EvenNumber> = t.recursion('EvenNumber', () =>
      t.record({
      type: t.literal('even'),
      next: t.optional(OddNumber, { forceUndefinedDefault: true }),
      }),
      );

      const OddNumber: t.Type<OddNumber> = t.recursion('OddNumber', () =>
      t.record({
      type: t.literal('odd'),
      next: t.optional(EvenNumber, { forceUndefinedDefault: true }),
      }),
      );