Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Typescript's template literal types are awesome when creating values that have to match a specific format.

But depending on the format it can sometimes be tricky to narrow a string back down to that format.

We have type guards to do that narrowing. (see: https://www.typescriptlang.org/docs/handbook/2/narrowing.htm..., but their older example is a little easier to read: https://www.typescriptlang.org/docs/handbook/advanced-types....)

If writing the check is too tricky, sometimes it can just be easier to track the type of a value with the value (if you can be told the type externally) with tagged unions (AKA: Discriminated unions). See: https://www.typescriptlang.org/docs/handbook/typescript-in-5...

And if the formats themselves are generated at runtime and you can use the "unique" keyword to make sure different kinds of data are treated as separate (see: https://www.typescriptlang.org/docs/handbook/symbols.html#un...).

You can combine `unique symbol` with tagged unions and type predicates to make it easier to tell them apart.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: