1

I'm building a set of services with a lot of different ID types flying around. Rather than just calling them all nodeId: string, I'd like to have a.) Typing and b.) Validation of format. So we end up with something like

export class LogicalId extends String {
    constructor(value: string) {
        if (!/somepattern/.exec(value) {
            throw new ValidationError(...);
        }
        super(value);
    }
}

Is there a better approach here that will give me types across the codebase as well as giving runtime checking?

2
  • Do you need compile-time or run-time type check? Commented Dec 24, 2016 at 1:30
  • I'd like to have both, ideally. Commented Dec 24, 2016 at 1:38

2 Answers 2

2

Using regular expressions to define types isn't currently a supported feature of TypeScript, but it's a feature issue that's being discussed.

The best workaround for the time being would be to create a wrapper class that you pass around instead of a raw string.

Sign up to request clarification or add additional context in comments.

2 Comments

Is that exactly what I suggest in the OP? How do you have upvotes without having said anything of merit, I wonder?
@ap Sometimes people ask questions in which they say "here's what I'm doing, is there a better way?" and sometimes the answer unequivocally is "what you're doing is the only way (right now)". I sure wish there'd be a better way (e.g. something like the proposal faraz linked to) but sometimes we just don't get our wishes.
1

I've updated @fny's answer to reflect the current (still ongoing) discussion of regex string types but you should check out Template Literal Types which are an official part of current TypeScript releases and may provide what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.