Reputation: 3198
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?
Upvotes: 1
Views: 116
Reputation: 123058
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.
Upvotes: 1
Reputation: 33517
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.
Upvotes: 2