Unions and Narrowing in TypeScript
Tags: typescript, learningtypescript, beginners
Published: 2023-02-25 20:55:49

## 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;

- <u>Unions:</u>
Allowing us to assign two or more types of values to a variable that results in defining possible types of it


- <u>Narrowing:</u>
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

```typescript
// 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)

```

- Example 2

```typescript
// 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

```

## Narrowing

- Example 1: conditional check

```typescript
// 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

```

- Example 2: typeof check

```typescript
// 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"

```

- Example 3: Logical operators

```typescript

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"

```

## 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

- [Learning Typescript](https://www.oreilly.com/library/view/learning-typescript/9781098110321/?_gl=1*afxut*_ga*NTE1MjkzMTQxLjE2Nzc4NzgwOTg.*_ga_092EL089CH*MTY3Nzg3ODA5OC4xLjEuMTY3Nzg3ODEwNS41My4wLjA.)