DEV Community

Saulo Dias
Saulo Dias

Posted on

3 2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more