The base type
The refined type (must extend T)
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)
Creates a
RefineTypeGuardthat checks that the value is of typeTand passes therefinementfunction.This is useful for:
Can be shortened with
TypeGuard.refine.Warning
Using
isRefinecan 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.