Is it possible to simplify the type that is being shown in the type-tooltip that is visible when I hover over a variable in Typescript?
I have the following code:
type Debug<T> = {
[key in keyof T]: T[key]
}
type Chainable<Acc = {}> = {
option: <K extends string, V>(key: K, value: V) => Chainable<Acc & {[k in K]: V}>;
get: () => Debug<Acc>;
}
declare const config: Chainable
const result = config
.option('foo', 123)
.option('name', 'type-challenges')
.option('bar', { value: 'Hello World' })
.get()
type X = typeof result;
When I hover over result
variable I get:
[
However, when I hover over type X
I see:
Questions:
playground
It seems it is possible to create a utility type that will do the flattening automatically. So, there is no need to dissect the type the way @zecuria did.
type Chainable<Acc = {}> = {
option: <K extends string, V>(key: K, value: V) => Chainable<Acc & {[k in K]: V}>;
get: () => Util_FlatType<Acc>;
}
type Util_FlatType<T> = T extends object ? { [K in keyof T]: Util_FlatType<T[K]> } : T
Util_FlatType is stolen from here
You could do something like:
type Chainable<Acc = {}> = {
option: <K extends string, V>(key: K, value: V) => Chainable<{[k in K | keyof Acc]: k extends keyof Acc ? Acc[k] : V}>;
get: () => Debug<Acc>;
}
Basically this is doing the same thing as what you're doing but in a more round about way.
Instead of relying on &
parameter which will pollute the hover hint. You can effectively recreate the entire object from scratch.
This is achieved by using k in K | keyof Acc
as the key but it also means you need a conditional type for the value.
I imagine this maybe less performant but honestly i don't think it will make the most difference.
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With