Skip to content

suggestion: correct types of flag booleans for RegExp literals #21290

Closed
@ghost

Description

TypeScript Version: 2.7.0-dev.20180118

Search Terms
flag
flags
literal
literals
pattern
patterns
regex
regexes
RegExp
RegExps
regular expression
regular expressions

Code

// the same thing also happens with flags other than sticky but the example just uses it

type Sticky = RegExp & {sticky: true};

// both error:
// Type 'RegExp' is not assignable to type 'Sticky'.
//   Type 'RegExp' is not assignable to type '{ sticky: true; }'.
//     Types of property 'sticky' are incompatible.
//       Type 'boolean' is not assignable to type 'true'.
const re1: Sticky = /test/;
const re2: Sticky = /test/y;

if (!(/a/y.sticky)) { console.log("should error as unreachable"); }
if (/a/y.global) { console.log("should error as unreachable"); }

Expected behavior:

the type Sticky should be compatible with any regex that has the y flag, and incompatible with those that don't

the type of /a/y.sticky should be true and /a/y.global should be false

Actual behavior:

typescript doesn't seem to care about the flags and always treats sticky and other ones as boolean even when the flags could be read from the regex literal

if you have a function that only works with sticky/global/other weird regexps, you'll have to check the flag yourself with pattern.sticky or pattern.flags.includes("y")

the properties are all read-only so the feature shouldn't be unsafe to have

tl;dr:

  • the flag booleans like RegExp.prototype.sticky should be set to the right boolean literal types when their values can be read from the regular expression literal (which is always)

  • as an extra, there are also the two strings RegExp.prototype.flags and RegExp.prototype.source that could be read from the literal (and RegExp constructor could also set them)

    • note: the flags string is sorted alphabetically

Playground Link:

https://www.typescriptlang.org/play/

Related Issues:

couldn't find any

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions