utilitypes-ts
    Preparing search index...

    Type Alias TypeGuard<Target, Source>

    TypeGuard: (value: Source) => value is Target

    Represents a type guard function that narrows a value from Source to Target.

    A TypeGuard is a function that takes a value of type Source and returns a boolean indicating whether the value is of type Target. When it returns true, TypeScript narrows the value to Target.

    Type Parameters

    • Target extends Source

      The type to narrow to

    • Source = unknown

      The input type (defaults to unknown)

    Type Declaration

    const isString: TypeGuard<string> = (value: unknown) => typeof value === "string";

    const value: unknown = "hello";

    if (isString(value)) {
    // value is now string
    value.toUpperCase();
    }
    type Input = string | number;

    const isNumber: TypeGuard<number, Input> = (value: Input) => typeof value === "number";

    const value: Input = 42;

    if (isNumber(value)) {
    // value is now number
    value.toFixed(2);
    }