View profile

All Things Typescript Newsletter - Issue #9

Maina Wycliffe
Maina Wycliffe
Good morning; I hope you had a great weekend. I would like to start by apologizing for not sending last week’s issue, I was feeling unwell, and I could not publish an issue for the week. In this issue, we will look into writing types with better type safety using Discriminated Unions and will have curated tweets and articles from the last two weeks.
I hope you have a great week ahead and don’t forget to follow me on Twitter - @mwycliffe_dev and if you have any questions, ideas, or feedback, my DMs are open to everyone.

Better Type Safety with Discriminated Unions
If we want to get the most out of Typescript Types, we need to ensure that we are specific in how we define them. A loosely defined type might be better than not having them, but their impact will not be as good as having Types that properly reflect our data.
Let’s take the simplest example I can think of - Shapes. In shapes, we can have Circles, Rectangles, Squares, etc., you get the idea. There is no way you can have a single type alias that can cover all shapes without compromising on something.
If we were to define a Shape type alias for just the above three shapes, it would need to account for the possibility that all fields are not there for all shapes, i.e., Circle only has a radius, which doesn’t exist in either Rectangle or Square, while the circle doesn’t have either width or height. As you can imagine, our problem only becomes more extensive as you add more shapes.
So, our type alias would look like this.
type Shape = {
radius?: Number; // For Circle
length?: Number; // For Rectangle
width?: Number; // For Rectangle
side?: Number; // For Square side Length
From the above example, the type alias above is not very useful since if you had a circle, you could easily leave out all fields or add all of them to Shape and typescript will not be able to help you at all; all it can do is offer autocompletion hints for you.
And discriminated unions come to the rescue.
Discriminated Unions
Instead of defining a single type alias that loosely much all of our possible types, we can define three different types, each containing a literal field member indicating what shape we have.
For instance, the type for Rectangle would look like this:
type Rectangle = {
shape: "Rectangle",
length: number;
width: number;
And the same applies to both Circle and Square:
type Circle = {
shape: "Circle"
radius: number;
type Square = {
shape: "Square";
side: number;
And then, we can use a union of the three to declare a type alias of shape that can only be a single type of the above.
type Shape = Square | Rectangle | Circle;
Now, with our new Type shape, we have to indicate the shape field, and then typescript is going to use the shape field value to determine the fields that are required for the Type you are creating.
For instance, the shape Circle can only contain a radius property, and if you tried to add, let’s say, width, you will get an error:
const x: Shape = {
shape: "Circle",
radius: 5,
width: 5, // Error ---> Object literal may only specify known properties, and 'width' does not exist in type 'Circle'.
This offers a much better type safety as the shape field can now be strictly enforced depending on which you want, and you can now narrow the types based on the field shape.
if(shape.shape === "Circle") {
// the type is now a Circle only
This gives you peace of mind when using and creating objects compared to the loosely defined type we had initially.
I hope you found today’s lesson illuminating, and if you have any questions, please feel free to reach out to me.
Announcement 📢
Top Articles 📙
Matt Pocock
🔥 TypeScript Error Translator for VSCode 🔥

Tired of TypeScript errors? Translate them to human-readable language right in your IDE.

🪄 Download the extension:

🖥️ Or try the online playground:
Michael Hoffmann
💡 JavaScript Tip:

Create a deep copy of an object using structuredClone
TypeScript protip: accept any string, but suggest some specific values on autocomplete.
Matt Pocock
🔥 TypeScript Tip #21 🔥

If you're thinking about putting a TypeScript package up to NPM, you should be considering preconstruct. It makes setup EXTREMELY easy and takes many decisions out of your hands.

Here, we get a package ready for release in under 2 minutes.
Mini Bhati
#Typescript Tip: Keyof Type Operator

It takes an object type and creates a union type of its keys.

It is useful in creating types from other types as it extracts all the keys.

It constructs a union single string literal type of the keys
Wes Bos
🔥 Four ways to define an object type in TypeScript
Did you enjoy this issue? Yes No
Maina Wycliffe
Maina Wycliffe @mwycliffe_dev

Hand-picked typescript and related content on a weekly basis to help you improve your skills and knowledge.

In order to unsubscribe, click here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Created with Revue by Twitter.