Home > Software engineering >  Simplifying typescript types inside type popup
Simplifying typescript types inside type popup

Time:11-25

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

CodePudding user response:

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

CodePudding user response:

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

  • Related