Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1884

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 26, 20242024-11-26T12:18:08+00:00 2024-11-26T12:18:08+00:00

Typescript: Create a Union from a Type

  • 62k

Originally written at https://matiashernandez.dev

How can you transform a Typescript Type into a Union Type? And most important, Why would you want to do that?

A few days ago, I encountered myself refactoring a code from using multiple useState that handled related states into a useReducer.

My rule of thumb is: If you have 3 related useState, you should move that to be a useReducer

The issue came because the state was a vast set of properties, and I wanted to cut back the time of refactoring, so I want to reuse some of the previous code.

So, I decided that I needed to create the actions for this new reducer based on the names of the State, so basically created a union type based on the State type.

So, the use case:

  • I had a type to represent a State
  • I want to create a list of actions based on that State

The goal was to do something like the following snippet.

type State = {   searchKeyWords: string;   isSlidingPanelOpen: boolean;   selectedJobDocumentId: number; }  // I want to create this  type Actions = {   type: 'searchKeyWords',   payload: string } | {   type: 'isSlidingPanelOpen',   payload: boolean } | {   type: 'selectedJobDocumentId',   payload: number }  /// So it can be used like this function reducer(state: State, action: Actions) {   switch(action.type){     case 'searchKeyWords':       return {         ...state,         searchKeyWords: action.payload       }     case 'isSlidingPanelOpen':       return {           ...state,           isSlidingPanelOpen: action.payload         }     case 'selectedJobDocumentId':       return {         ...state,         selectedJobDocumentId: action.payload       }     default:       return state   } } 
Enter fullscreen mode Exit fullscreen mode

The idea is to automatically take the State type to create the Actions type.

I needed a utility type that takes in an unknown type and spits out a Union with a specific shape to achieve this behavior.

So, a clear use case for Generics and Mapped Types.

🤔 Why? Because generics are the way to write reusable types.

More on that in this Twitter thread

Mapped Types:

The main idea of this is to take the properties > of a type T to create a new type by using those > properties in another way

Let's create a new Unionize utility type that will take a generic named T that extends an object.

The extends keyword here acts as a way to restrict the type of T to be like an object

This type will iterate over the keys of T and map those to a new shape where each key of T will hold a new object shape.

/**  * Create an Union type from an Object type  * that will use the Object key as `type` entry and the  * Object value as `payload`  */ type Unionize<T extends object> = {     [k in keyof T]: { type: k; payload: T[k] }; }[keyof T]; 
Enter fullscreen mode Exit fullscreen mode

Let's use it!!

type State = {   searchKeyWords: string;   isSlidingPanelOpen: boolean;   selectedJobDocumentId: number; }  /**  * Create an Union type from an Object type  * that will use the Object key as `type` entry and the  * Object value as `payload`  */ type Unionize<T extends object> = {     [k in keyof T]: { type: k; payload: T[k] }; }[keyof T];  // I want to create this  type Actions = Unionize<State>  /// So it can be used like this function reducer(state: State, action: Actions) {   switch(action.type){     case 'searchKeyWords':       return {         ...state,         searchKeyWords: action.payload       }     case 'isSlidingPanelOpen':       return {           ...state,           isSlidingPanelOpen: action.payload         }     case 'selectedJobDocumentId':       return {         ...state,         selectedJobDocumentId: action.payload       }     default:       return state   } } 
Enter fullscreen mode Exit fullscreen mode

Check it out in the typescript playground

Follow me on Twitter ❤️ Support my content

programmingtypescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.