DEV Community

Saulo Dias
Saulo Dias

Posted on

String Patterns in TypeScript

While we wait for a regex type in TypeScript, starting on TypeScript 4.1 we can make use of a very neat trick to create string patterns validations which can come in handy for some simple use cases.

I'm using Leonardo Victor's approach to query endpoints in multiple APIs using the Angular HttpClient.

By making use of string patterns I'm able to validate the urls to some extent.

type ApiAlias = 'my-api' | 'third-party-api' | 'another-api';

type ApiUrl = `@${ApiAlias}/${string}`;

const MY_ENDPOINT: ApiUrl = '@my-api/myendpoint';

const ANOTHER_ENDPOINT: ApiUrl = '@thirdparty-api/anotherendpoint';
Enter fullscreen mode Exit fullscreen mode

TypeScript Playground

ANOTHER_ENDPOINT will throw an error because thirdparty-api has a typo. It's missing a hyphen, and should be third-party-api.

Go check out Leonardo Victor's post if you're interested in this implementation!

This post was inspired by this Stack Overflow thread. Let me know if things have changed by the time you're reading this, so I can keep this up to date.

Discussion (0)