Some (Michael ) =>

submited by
Style Pass
2023-03-19 22:00:08

In this blog post, we will discuss slightly advanced TypeScript features such as union types, generics, and conditional types. We will explore how these features interact when attempting to create type-safe function overloads, a common challenge faced by developers using TypeScript.

This post was originally notes from an impromptu presentation I gave during a work "lunch and learn" session a couple of years ago. I've noticed that many people find this area of TypeScript to be frustrating as they try to combine different language features, often ending up confused. Let's dive in and learn how to avoid some common pitfalls.

Before we jump in, let's have a quick refresher on three TypeScript features: union types, generics, and conditional types. Feel free to skip if you're already familiar with these concepts.

In the example above, T1 is a union type that can either be a string "tan" or an object of type Yan. The Tethera type is a union of two different object shapes, distinguished by their common type property. These are typically called discriminated unions in TypeScript, and elsewhere might be called tagged unions, disjoint unions, or sum types. TypeScript uses the language's control flow constructs to "narrow" union types, as demonstrated with the value t above.

Leave a Comment
Related Posts