FG
๐ŸŒ Web & Full-StackMicrosoft

Suggestion: Regex-validated string type

Freshabout 21 hours ago
Mar 14, 20260 views
Confidence Score95%
95%

Problem

There are cases, where a property can not just be any string (or a set of strings), but needs to match a pattern. [code block] It's common practice in JavaScript to store color values in css notation, such as in the css style reflection of DOM nodes or various 3rd party libraries. What do you think?

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Regex-Validated String Type for CSS Colors

Medium Risk

The current implementation allows any string as a valid input for properties that require specific formats, such as CSS color values. This can lead to runtime errors or unexpected behavior when invalid strings are processed. By enforcing a regex pattern, we can ensure that only valid CSS color formats are accepted.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Define Regex Pattern for CSS Colors

    Create a regex pattern that matches valid CSS color formats, including hex codes, RGB, RGBA, HSL, and HSLA.

    typescript
    const cssColorRegex = /^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})|rgba?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(,\s*(0|1|0?\.\d+)?)?\)|hsla?\(\d{1,3},\s*\d{1,3}%\s*,\s*\d{1,3}%(,\s*(0|1|0?\.\d+)?)?\))$/;
  2. 2

    Create a TypeScript Type Guard

    Implement a type guard function that checks if a given string matches the defined regex pattern for CSS colors.

    typescript
    function isValidCssColor(color: string): color is string { return cssColorRegex.test(color); }
  3. 3

    Integrate Type Guard into Property Setter

    Modify the setter for the property that requires a CSS color to use the type guard, ensuring only valid colors are accepted.

    typescript
    set color(value: string) { if (!isValidCssColor(value)) throw new Error('Invalid CSS color format'); this._color = value; }
  4. 4

    Update Documentation and Examples

    Revise the documentation to include examples of valid CSS color formats and the expected behavior when invalid formats are provided.

  5. 5

    Run Unit Tests

    Create and execute unit tests to verify that the type guard and setter function correctly handle valid and invalid CSS color inputs.

    typescript
    test('valid color', () => { expect(isValidCssColor('#fff')).toBe(true); }); test('invalid color', () => { expect(() => { color = 'invalid'; }).toThrow('Invalid CSS color format'); });

Validation

To confirm the fix worked, ensure that valid CSS color strings are accepted without errors, while invalid strings trigger appropriate error messages. Run the unit tests and verify all pass successfully.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

typescriptcompilersuggestionneeds-proposaldomain:-literal-types