DEV Community

Cover image for Unions and Narrowing in TypeScript
Kento Honda
Kento Honda

Posted on • Updated on

Unions and Narrowing in TypeScript

Intro

This is my first memorable article to publish on the DEV community.

Currently, I am relearning TypeScript using the book "Learning TypeScript" by Josh Goldberg to gain a clear understanding of its core principles.

During my TypeScript learning journey, I found myself confused and mixing up two important concepts - "Unions and Narrowing".

As a result, I have decided to write an article to review what I have learned and share it with others who are also learning TypeScript like me.

What are the concepts of Unions and Narrowing?

Firstly, I summarized shortly about Unions and Narrowing in TypeScript below;

  • Unions:
    Allowing us to assign two or more types of values to a variable that results in defining possible types of it

  • Narrowing:
    Specifying value's allowed type by implementing conditional checks, typeof checks, logical operators, and so on

TypeScript is a powerful tool for declaring variable types, allowing us to receive notifications when attempting to insert variables into values of different types.

However, in some cases, we may need to allow variables to have multiple possible value types. In these scenarios, Unions are a useful feature for developers.

Sample codes for Unions and Narrowing

Here are some samples codes demonstrating the concepts of Unions and Narrowing;

Unions

From this section, I use the term "Union Type", implementing the concepts of Unions in codes. Variables that have Union Type have multiple (two or more) potential types.

  • Example 1
// Declaring Union Type

let union: string | number

// We can insert values with number type or string type to this union variable

union = 28  // ok, 28 is a number
union = "Gold"  // ok, Gold is a string

// Also, Union Type only allows us to assign values with types declared in it (In this case, we can only assign values with number type or string type)

union = false  // Error (Because boolean type does not exist in Union Type above)

Enter fullscreen mode Exit fullscreen mode
  • Example 2
// The variable "randomValue" has two possibilities of types; string or number 

(based on the result of Math.random() method)

let randomValue = Math.random() > 0.8 
? 28  // number
: "Gold"  // string

Enter fullscreen mode Exit fullscreen mode

Narrowing

  • Example 1: conditional check
// This variable has string value or number value

let randomValue = Math.random() > 0.8 
? 28  
: "Gold"

// Define a function returning the value type of parameter

function sampleFuncForRandomValue(value:string | number) {
 if(value === 28) {
  return "Value has number type"
 }
 else if(value === "Gold") {
  return "Value has string type"
 }
 else return "Nothing"
}

// Implement this function for checking the type of value for the randomValue variable

sampleFuncForRandomValue(randomValue)  // returns "Value has number type" or "Value has string type" based on the value type of randomValue variable

Enter fullscreen mode Exit fullscreen mode
  • Example 2: typeof check
// Declare the union variable

let union: string | number

// Define a function returning the value type of parameter

function sampleFunc(value:string | number) {
 if(typeof value === "number") {
  return "Value has number type"
 }
 else {
  return "Value has string type"
 }
}

// Let's play around sampleFunc function!

union = 28  // typeof union === "number"
sampleFunc(28)  // returns "Value has number type"

union = "Gold"  // typeof union === "string"
sampleFunc(union)  // returns "Value has string type"

Enter fullscreen mode Exit fullscreen mode
  • Example 3: Logical operators

let union: string | undefined;

// Currently, the type of value for the union variable is undefined.

union?.toLowerCase()  // returns "undefined"
union && toLowerCase()  // returns "undefined"

// Now, insert "GOLD" (string) into the union variable, and implement the same steps above. Let's see how it goes.

union = "GOLD"
union?.toLowerCase()  // ok, returns "gold"
union && union.toLowerCase() // ok, returns "gold"

Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, unions and narrowing are powerful and important concepts that TypeScript developers should know to write safer and more efficient code.

Union types allow for increased flexibility in the types of variables and parameters that can be accepted, while narrowing can help to ensure that code behaves as intended types of value.

At the end

Through writing this article, I have reviewed and improved my understanding of TypeScript by carefully ensuring the accuracy of my content.

Furthermore, I have come to realize that creating programming articles is an effective way to showcase and enhance my technical skills.

I am excited to continue writing and exploring new topics, even though I am not yet certain what my next article will be about!

References

Top comments (0)