3

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: [hovering over result variable 1

However, when I hover over type X I see: hovering over a typeof result

Questions:

  1. Why are those types shown differently? (Even though they represent the same thing)
  2. Is there a way to show the type like it's shown in the second screen?

playground

paroxyzm
  • 1,422
  • 2
  • 13
  • 29

3 Answers3

6

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

enter image description here

Util_FlatType is stolen from here

paroxyzm
  • 1,422
  • 2
  • 13
  • 29
1

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

zecuria
  • 728
  • 4
  • 9
1

This is a primary difference between the type keyword and the interface keyword. Interface names appear in tooltips but type names do not.

Ron Newcomb
  • 2,886
  • 21
  • 24