Function sanitizeLiteral

  • A type-safe string sanitizer supporting any set of chars while being capable of calculating the expected result as a static type if literal is provided as a name. Predicts the accurate output based on input types or errors (never) if function is guaranteed to fail in the runtime.

    Remarks

    It is designed to be rather performant at runtime (it uses RegExp under-the-hood), however be aware of long compilation times as TypeScript will have to do heavy calculations for function result in case of complex strings and character sets (a lot of operations are done in char-by-char manner, using infer and type recursion — there's a real chance that for very long literal strings TypeScript will just give up at calculations and end compilation with an error!).

    Throws

    • TypeError for unresolveable charset or invalid trimMode, RangeError for non-char values in replacement and Error for value which cannot be sanitized to the expected charset.

    Example

    // (const) regular: "fooBar3"
    const regular = "fooBar3" as const;
    // (const) mod1: "FOOBAR3"
    const mod1 = sanitizeLiteral(regular,"A-Z0-9");
    // (const) mod2: "foobarz"
    const mod2 = sanitizeLiteral(regular,"a-z","z");
    // (const) mod3: "oo_ar3"
    const mod3 = sanitizeLiteral(regular,"acdeghijklmnopqrstuvwxyz0-9","_");

    Since

    v1.0.0

    Type Parameters

    Parameters

    • value: V

      Value to sanitize. Should be a non-nullish string.

    • charset: C = ...

      A string that represents a set of characters. For ranges, only values from parseableRange are valid.

    • replacement: R = ...

      A char (i.e. string with length === 0) which should replace invalid characters inside the string.

    • trimMode: M = ...

      – Definies how string should be trimmed. Defaults to left (compatibility reasons).

    Returns sanitizeResult<V, C, R, M>

    • Original value for nullish values, sanitized string for anything else.