DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for TypeScript: ensure your strings are in the right format
Johan du Toit
Johan du Toit

Posted on

TypeScript: ensure your strings are in the right format

Turns out TypeScript allows you to type your string formats...

Example #1

type MyStringFormat = `${number} ${string} ${number}`;
const valid: MyStringFormat = "1 b 3"
const invalid: MyStringFormat = "a b c"
Enter fullscreen mode Exit fullscreen mode

Example #2

type Unit = 'C' | 'F' | 'K'

type Temp = `${number} ${Unit}`;
const validTemp: Temp = "273 K" // 0 C, 31.73 F
const invalidTemp: Temp = "0 B" // 0C, 31.73F, 273K (no spaces)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Forem is hiring a Senior Platform Engineer

If you're interested in ops and site reliability and capable of dipping in to our Linux stack, we'd love your help shoring up our systems!