Use 'in' operator to transform a union to another union

The challenge for today is to take this union type here type user type post type comment.

export type Entity =
  | {
      type: "user"
    }
  | {
      type: "post"
    }
  | {
      type: "comment"
    }

And then dynamically add id to the type which is going to be userId postId and commentId. As you can see bellow, we are manually defining the types of those id properties.

type EntityWithId =
  | {
      type: "user"
      userId: string
    }
  | {
      type: "post"
      postId: string
    }
  | {
      type: "comment"
      commentId: string
    }

We can automate this with TypeScript

First we'll use the [Key in Type] syntax to iterate over our Entity type and set the type property to the key which we've named EntityType.

type EntityWithId = {
  [EntityType in Entity["type"]]: {
    type: EntityType
  }
}

We'll want to turn this object into a union type. We do this by applying an index operation to the object. In this case we'll use [Entity["type"]] to get the value of the type property.

type EntityWithId = {
  [EntityType in Entity["type"]]: {
    type: EntityType
  }
}[Entity["type"]]

and this means. now that we now have our type comment or type user

const result = (EntityWithId = {
  type: "comment",
})

But we haven't really added anything here. We just sort of created the same type again.

What we need to do is say that we want type property AND our id property. We can create the dynamic id property using Record utility type. This is used to define a key and the type of its value. We'll make the key dynamic by using string interpolation.

type EntityWithId = {
  [EntityType in Entity["type"]]: {
    type: EntityType
  } & Record<`${EntityType}Id`, string>
}[Entity["type"]]

So now in our result object we can set commentId to a string.

const result: EntityWithId = {
  type: "comment",
  commentId: "123",
}

so in EntityWithId where we set the type and use & Record..., we're saying we have have the type of EntityType AND the Record which is another way of saying we have an object with a key of ${EntityType}Id and a value of string

We can then create objects for user and post.

const userResult: EntityWithId = {
  type: "user",
  userId: "123",
}

const postResult: EntityWithId = {
  type: "post",
  postId: "123",
}

Transcript

0:00 Folks, the challenge for today is to take this union type here, type user, type post, type comment, and dynamically add the ID type, which is going to be userID, postID, and commentID. As you can see, the EntityWithID is currently not really...we could be auto generating this and we're not. Let's try and improve on this.

0:18 We're going to say type EntityWithID = -- we're going to use the sort of same trick as we did last time -- which it's going to be [EntityType in Entity ["type" ]. This is going to be an object where the type is the EntityType. Now, so far, what this will do is we'll get to this point where we have comments where the type is 'comment'.

0:47 We're doing pretty well there, but really what we needed to turn this into a union. To turn into a union, we basically go EntityType here. This means now that we now have our type: 'Comment' or type: 'User', but we haven't really added anything here. We just created the same type again. We haven't added the IDs.

1:05 The way that we do this is we say, "OK, we've got this object here, which is representing this." We say and we're going to make a record where it's going to be entity type. In fact, we're going to use a new string literal type where it's going to be entity type and then ID. That's going to be a string.

1:24 now commentID is going to appear 1, 2, 3. This little thing here, we're basically saying we have the type entity type and the record, which is another way of saying a string or rather an object with this is the key, with this as the value of that key.

1:44 If we remove this little end, then commentID no longer exists. If we remove this bit here, then we don't need to pass the type anymore. We just pass the commentID. There we go. That's how we handle it. We've used a little bit of a quite modern TypeScript here to handle this, but it's perfectly possible to do this, of course, if we didn't then go post, then we need to pass in a post ID.

2:05 Thanks so much for your time.

Transform a union to another union, using the 'in' operator as a kind of for-loop.

This pattern can be used for almost any kind of transformation - here, I add a dynamic key.

Discuss on Twitter

More Tips

Play Type Predicates

Type Predicates

1 min

Play TypeScript 5.1 Beta is OUT!

TypeScript 5.1 Beta is OUT!

2 mins

Play How to Name your Types

How to Name your Types

4 mins

Play Don't use return types, unless...

Don't use return types, unless...

4 mins

Play TypeScript 5.0 Beta Deep Dive

TypeScript 5.0 Beta Deep Dive

6 mins

Play Conform a Derived Type Without Losing Its Literal Values

Conform a Derived Type Without Losing Its Literal Values

1 min

Play Avoid unexpected behavior of React’s useState

Avoid unexpected behavior of React’s useState

1 min

Play Understand assignability in TypeScript

Understand assignability in TypeScript

2 mins

Play Compare function overloads and generics

Compare function overloads and generics

1 min

Play Use infer in combination with string literals to manipulate keys of objects

Use infer in combination with string literals to manipulate keys of objects

1 min

Play Access deeper parts of objects and arrays

Access deeper parts of objects and arrays

1 min

Play Ensure that all call sites must be given value

Ensure that all call sites must be given value

1 min

Play Understand how TypeScript infers literal types

Understand how TypeScript infers literal types

1 min

Play Get a TypeScript package ready for release to NPM in under 2 minutes

Get a TypeScript package ready for release to NPM in under 2 minutes

1 min

Play Use assertion functions inside classes

Use assertion functions inside classes

1 min

Play Assign local variables to default generic slots to dry up your code and improve performance

Assign local variables to default generic slots to dry up your code and improve performance

2 mins

Play Know when to use generics

Know when to use generics

2 mins

Play Map over a union type

Map over a union type

1 min

Play Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

1 min

Play Use generics to dynamically specify the number, and type, of arguments to functions

Use generics to dynamically specify the number, and type, of arguments to functions

1 min

Play Use 'declare global' to allow types to cross module boundaries

Use 'declare global' to allow types to cross module boundaries

2 mins

Play Turn a module into a type

Turn a module into a type

2 mins

Play Create autocomplete helper which allows for arbitrary values

Create autocomplete helper which allows for arbitrary values

2 mins

Play Use deep partials to help with mocking an entity

Use deep partials to help with mocking an entity

1 min

Play Throw detailed error messages for type checks

Throw detailed error messages for type checks

1 min

Play Create a 'key remover' function which can process any generic object

Create a 'key remover' function which can process any generic object

1 min

Play Use generics in React to make dynamic and flexible components

Use generics in React to make dynamic and flexible components

1 min

Play Create your own 'objectKeys' function using generics and the 'keyof' operator

Create your own 'objectKeys' function using generics and the 'keyof' operator

1 min

Play Write your own 'PropsFrom' helper to extract props from any React component

Write your own 'PropsFrom' helper to extract props from any React component

1 min

Play Use 'extends' keyword to narrow the value of a generic

Use 'extends' keyword to narrow the value of a generic

1 min

Play Use function overloads and generics to type a compose function

Use function overloads and generics to type a compose function

2 mins

Play Decode URL search params at the type level with ts-toolbelt

Decode URL search params at the type level with ts-toolbelt

2 mins

Play Derive a union type from an object

Derive a union type from an object

2 mins