You can do some really clever things with default parameters of generics and they can really help tidy up really complicated looking generic signatures.
Here we've got an object where what we wanna do is extract the values of the keys that start with a from this object. And so this union, NewUnion it's looking at the a, a2, a3 in our Obj.
export type Obj = {
a: "a"
a2: "a2"
a3: "a3"
b: "b"
b1: "b1"
b2: "b2"
}
type ValuesOfKeysStartingWithA<Obj> = {
[K in Extract<keyof Obj, `a${string}`>]: Obj[k]
}[Extract<keyof Obj, `a${string}`>]
type NewUnion = ValuesOfKeysStartingWithA<Obj>
And if I change a to "FOO", for example, it's extracting the values of those keys that start with A. But it's a pretty messy type signature because there's quite a bit of duplication here. In ValuesOfKeysStartingWithA we're extracting the key of the object, and we're saying we only want those keys that start with a.
type ValuesOfKeysStartingWithA<Obj> = {
[K in Extract<keyof Obj, `a${string}`>]: Obj[k]
}[Extract<keyof Obj, `a${string}`>]
And then we return the part of the object that corresponds to that key. And then we do it a second time because we need to map over the object in order to pull those values out.
We can actually reduce the duplication by saving it to a local variable.
And you might think, where on earth would I save it here? Well, you can stick it inside the default parameters of a new private generic.
So to start, I'll add the _ExtractedKeys type variable to ValuesOfKeysStartingWithA. And TypeScript is yelling at me, because it wants two type parameters.
But, I can actually set a default type parameter to _ExtractedKeys, and I can set it to:
Extract<keyof Obj, `a${string}`>
Now that our keys are extracted we can get rid of both instances of Extract and name them _ExtractedKeys instead.
type ValuesOfKeysStartingWithA<
Obj,
_ExtractedKeys = Extract<keyof Obj, `a${string}`>
> = {
[K in _ExtractedKeys]: Obj[k]
}[_ExtractedKeys]
But, we're going to get an error with our first use of _ExtractedKeys saying that it's is not assignable to type string or number or blah, blah, blah. That's because it takes the value from the type of the generic.
So if we add to our _ExtractedKeys generic and say it extends keyof Obj, then it starts working because we say _ExtractedKeys extends the key of the object.
type ValuesOfKeysStartingWithA<
Obj,
_ExtractedKeys extends keyof Obj = Extract<keyof Obj, `a${string}`>
> = {
[K in _ExtractedKeys]: Obj[k]
}[_ExtractedKeys]
This is now much easier to read and our union still stays the same.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.