isguard-ts
    Preparing search index...

    Function isRefine

    • Creates a RefineTypeGuard that checks that the value is of type T and passes the refinement function.

      This is useful for:

      • Branded types.
      • Template literals.
      • Any type guard that doesn't have a built-in implementation.

      Can be shortened with TypeGuard.refine.

      Warning

      Using isRefine can be unsafe as it allows implementing potentially incorrect logic. Ensure that your refinement function correctly narrows the type and does not produce false positives. Use with caution.

      Type Parameters

      • T

        The base type

      • R

        The refined type (must extend T)

      Parameters

      • isBase: TypeGuard<T>

        The base type guard to refine

      • refinement: (value: T) => value is R

        A function that checks the additional constraints

      Returns RefineTypeGuard<T, R>

      A type guard for the refined type R

      type UUID = Tagged<string, "UUID">;

      const isUUID = isRefine(isString, (value: string): value is UUID => {
      return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
      });

      isUUID("123e4567-e89b-12d3-a456-426614174000"); // true
      isUUID("not-a-uuid"); // false
      isUUID(123); // false
      type Farewell = `Bye ${string}`;

      const isFarewell = isString.refine((value: string): value is Farewell => {
      return value.startsWith("Bye ");
      });

      isFarewell("Bye world"); // true
      isFarewell("Hello world"); // false
      type EvenNumber = Tagged<number, "EvenNumber">;

      const isEvenNumber = isNumber.refine((value: number): value is EvenNumber => {
      return value % 2 === 1; // Incorrect logic for even numbers
      });

      isEvenNumber(2); // false (should be true)
      isEvenNumber(3); // true (should be false)