Home > Software design >  VSCode type preview is not simplifying type
VSCode type preview is not simplifying type

Time:03-12

I've got a fairly complicated type derived from another. In the type declaration and in type annotations the type is correctly derived:

Correctly derived type on declaration

However, when hovering actual JS variables of the specified type, the type is not simplified and instead the popup shows the chain of all the applied type modifiers:

enter image description here

Is there any way to force VSCode to always show the simplified type?

TS Version: 4.6.2 VSC Version: 1.65.1

CodePudding user response:

At the moment there's no way to alter the types that VS Code shows on hover, but you can define an identity type to get rid of all the type applications.

Here's a recursive one that also properly handles functions:

// Normalize type by recursively applying any type aliases and merging explicit intersections.
export type Normalize<T> =
  T extends (...args: infer A) => infer R ? (...args: Normalize<A>) => Normalize<R>
  : [T] extends [any] ? {[K in keyof T]: Normalize<T[K]>} : never 

For example:

type A = { a: string }
type B = { b: number }
type NotNormalized = A & B // inferred type: A & B
type Normalized = Normalize<NotNormalized> // inferred type: { a: string, b: number }

The type Normalize<User> should show you the normalized User type on hover. Other versions of Normalize (often called Expand) are possible, depending whether you want to normalize only the top level or recursively, and whether you need to deal with function properties.

TypeScript playground

  • Related