Derive a union type from an object
Sometimes you may need want to type an object which has several different optional keys, but all with the same type. We can map over a union type to accomplish this instead of chaining |
in an object type.
I start with some code that looks like this
type SingleFruitCount =
| {
apple: number;
}
| {
banana: number;
}
| {
pear: number;
export const fruitCount = {
apple: 1,
pear: 4,
banana: 26,
}
type SingleFruitCount =
| {
apple: number
}
| {
banana: number
}
| {
pear: number
}
const singleFruitCount: SingleFruitCount = {
banana: 12,
}
Let's start improving this. First I will make a FruitCount
type out of my fruitCounts
object, then I'm going to make a new type called NewSingleFruitCount
.
type FruitCounts = typeof fruitCounts
type NewSingleFruitCount = {
[K in keyof FruitCounts]: {}
}
What this is doing is its taking each key in FruitCounts
and setting its type to an empty object. So when I use it, TypeScript will be expecting a shape like this.
const singleFruitCount: NewSingleFruitCount = {
apple: {},
pear: {},
banana: {},
}
But, I want the properties to be numbers.
type NewSingleFruitCount = {
[K in keyof FruitCounts]: {
[K2 in K]: number
}
}
As you can see, if I just do that, I still haven't quite got a union type. I get this odd nested structure, and I will still have to have every possible fruit present.
const singleFruitCount: NewSingleFruitCount = {
apple: {
apple: 2,
},
pear: {
pear: 4,
},
banana: {
banana: 26,
},
}
So, what I'm going to do is map over our NewSingleFruitCount
type to get rid of those parent keys, and fully create my union type.
type NewSingleFruitCount = {
[K in keyof FruitCounts]: {
[K2 in K]: number
}
}[keyof FruitCounts]
And with that, I can now assign our singleFruitCount
how I'd like.
const singleFruitCount: NewSingleFruitCount = {
apple: 2,
}
Transcript
0:00 Hello, folks. For this TypeScript tip, I'm going to show you how to change this fruitCounts object here into a union type. Imagine our code is a little bit crap at the moment because, really, we want to be deriving this type, this union of objects, from this object. I'm going to show you how to do it.
0:20 What we're going to do is we're going to name this NewSingleFruitCount, and I'm going to create a new type here, which is type NewSingleFruitCount. This is going to be an object. This is going to get a little bit funky here. First of all, I'm going to make a type out of this const up here, which is going to be type FruitCounts equals typeof fruitCounts.
0:44 Inside here, I'm going to go K in keyof FruitCounts is going to be...Let's, first of all, make it an object. This is going to be interesting because now, what we're going to have is fruitCounts is expecting this shape, where apple is now an empty object. In fact, it's even asking for apple is apple, which is an empty object or something crazy.
1:04 Essentially, what we have now is -- This is correct -- we're now looking for a shape like this. Inside, here we can specify anything and it will get put into here. We can say wow true, for instance, and now, all of these will require wow true. We don't want that. We actually want to take this key and we want to represent it as this apple number.
1:29 We're going to say K2 in K is a number. Now, each of these now require apple as a number. This is going to be 12, for instance, whatever. This is still not quite what we wanted. Even though we have all of this stuff represented, we've got this nice dynamic key here, it's still not quite a union.
1:50 To turn it into a union, all we need to do is map over these keys and essentially get rid of them. What we're going to do is just call these and say keyof FruitCounts. Maybe call isn't the right there. Now, what we have is we can have apple 2, and it satisfies it. There you go. This is how you turn a object type into a union.
Learn how to derive a union type from an object - an incredibly useful switcheroo that's at the heart of most TS magic out there.
More Tips
Type Predicates
1 min
TypeScript 5.1 Beta is OUT!
2 mins
How to Name your Types
4 mins
Don't use return types, unless...
4 mins
TypeScript 5.0 Beta Deep Dive
6 mins
Conform a Derived Type Without Losing Its Literal Values
1 min
Avoid unexpected behavior of React’s useState
1 min
Understand assignability in TypeScript
2 mins
Compare function overloads and generics
1 min
Use infer in combination with string literals to manipulate keys of objects
1 min
Access deeper parts of objects and arrays
1 min
Ensure that all call sites must be given value
1 min
Understand how TypeScript infers literal types
1 min
Get a TypeScript package ready for release to NPM in under 2 minutes
1 min
Use assertion functions inside classes
1 min
Assign local variables to default generic slots to dry up your code and improve performance
2 mins
Know when to use generics
2 mins
Map over a union type
1 min
Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig
1 min
Use generics to dynamically specify the number, and type, of arguments to functions
1 min
Use 'declare global' to allow types to cross module boundaries
2 mins
Turn a module into a type
2 mins
Create autocomplete helper which allows for arbitrary values
2 mins
Use deep partials to help with mocking an entity
1 min
Throw detailed error messages for type checks
1 min
Create a 'key remover' function which can process any generic object
1 min
Use generics in React to make dynamic and flexible components
1 min
Create your own 'objectKeys' function using generics and the 'keyof' operator
1 min
Write your own 'PropsFrom' helper to extract props from any React component
1 min
Use 'extends' keyword to narrow the value of a generic
1 min
Use function overloads and generics to type a compose function
2 mins
Decode URL search params at the type level with ts-toolbelt
2 mins
Use 'in' operator to transform a union to another union
2 mins