Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is there a way to create regex patterns to match strings? #280

Closed
alita-moore opened this issue Oct 10, 2021 · 3 comments
Closed

is there a way to create regex patterns to match strings? #280

alita-moore opened this issue Oct 10, 2021 · 3 comments

Comments

@alita-moore
Copy link

For example let's say I'm given a list of strings

const strings = [... unknown strings]

and I want to make sure that they start with @ both in runtime and in dev time; it would be helpful to be able to do something like

const strings: MatchinString</^@(?!\s)*/>[] = ["@string", "@string with space", "string_without_@"]
// and then I would get a linting error on "@string with space" and "string_without_@" 

Another use case here would be checking in runtime explicity

function assertMatchingString <T extends string>(maybeMatching: T): asserts T is MatchingString</^@(?!\s)*/> {
    if (!/^@(?!\s)*/.test(maybeMatching)) throw "error";
}

This would be especially useful in a setting where I want to perform code knowing that the strings are in the right format

// assume an inputString

assertMatchingString(inputString);
// now inputString would of the type of regex
someFunction(inputString) // this function would have a similar string definition in its input so that type comparisons can be made
@alita-moore
Copy link
Author

nevermind, it looks like this is mostly possible using opaque types

@sindresorhus
Copy link
Owner

You'll probably want to follow microsoft/TypeScript#41160

@alita-moore
Copy link
Author

oh very cool, ya that'd be sweet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants