NevNein
NevNein

Reputation: 547

VSCode type preview is not simplifying type

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

Upvotes: 1

Views: 915

Answers (1)

Oblosys
Oblosys

Reputation: 15116

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.
type Normalize<T> =
  T extends (...args: infer A) => infer R
  ? (...args: Normalize<A>) => Normalize<R>
  : {[K in keyof T]: Normalize<T[K]>}

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

Upvotes: 3

Related Questions