Repository: TypeScript
Issue: Hoist types in declarations or copy JSDoc comments to all copies of type
Labels: Suggestion,Needs Proposal

# Suggestion

## 🔍 Search Terms

- jsdoc
- jsdoc zod
- jsdoc missing
- hoist types

## ✅ Viability Checklist

<!--
   Suggestions that don't meet all these criteria are very, very unlikely to be accepted.
   We always recommend reviewing the TypeScript design goals before investing time writing
   a proposal for ideas outside the scope of the project.
-->
My suggestion meets these guidelines:

* [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
* [x] This wouldn't change the runtime behavior of existing JavaScript code
* [x] This could be implemented without emitting different JS based on the types of the expressions
* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals)


## ⭐ Suggestion

I stumbled upon problem while using Zod with TypeScript: it loses important JSDoc and produces GIANT declarations for complex schemas when emitting declaration file. This is because TypeScript duplicates the type declarations in generic types, and generic parameters that have default values and could safely be omitted. Neither does it copy JSDocs to duplicated types.

I was thinking how this can be solved and came up with idea of ‘type’ hoisting: compiler can hoist types that will be re-used, under safe names. See motivating example for more details.

Alternative solution to just copy JSDoc descriptions, but this will make already giant declaration even bigger, cause in complex types TypeScript can duplicate same property 5-10 times.

## 📃 Motivating Example

In the attached playground I defined `User` and `AuthenticatedUser` schemas. `User` has only `id` property, and `AuthenticatedUser` has `email` and inherits `id` from `User`. All properties have simple JSDoc comments to explain the meanings.

[Playground link](https://www.typescriptlang.org/play?ts=5.1.0-beta#code/JYWwDg9gTgLgBAbzgLzgXzgMyhEcBEyEAJvgNwBQFAxhAHYDO8ArgwKZQDK1AFmyAEM4AXhQA6CACMAVm2owAFAgpw4AegBUGuABU+cYMTgRMcGPtYc4GtSoPEAXOLrMQkjgoCUAGgppPlBQwAJ5gbHAAquxQIuIQzDBgCQA8IWEmcJZcvPwCAHyBtIzwAgl8dDDA1AIwbMRRHNx8grFZTblibAAetXTESnaa2nrhucAANnACxMRQbAwMxqbm4aUrFVU1dZnR1raqY+NOyGJMUMB0AOZenYITXr7+gWnhAIJlbBvVtfW7oifxRIpF4ZNblSrfOoNbLNfKBbqQWCIOxtHKCXyqMGfCFbX6NNECDGRaJE97rHE-aGPShAA)

When working with the original code you can write `type Test = AuthenticatedUser['email']`, hover over `['email']` and see the JSDoc comment for `email` property. However, if you use the declaration, and try to do the same thing, TypeScript will no longer show anything but that `email` is a string (useful, but also not).

This means that if you are writing a node package with some Zod schemas, e.g. you have a monorepo and `@org/api-schemas`, you cannot store ANY JSDoc comments. This can be a huge deal. Let's try to solve that.

If you look closely into declaration, you can notice that TypeScript copied default parameters of `ZodObject` that can be safely be omitted, let's do that.

<details><summary>Patch 1</summary>
<p>

```patch
--- a.d.ts	2023-04-30 22:27:58.780166540 +0000
+++ b.d.ts	2023-04-30 22:28:08.536152930 +0000
@@ -1,34 +1,12 @@
 import { z } from "zod";
-declare const userSchema: z.ZodObject<
-  {
-    /** The id of the user */
-    id: z.ZodNumber;
-  },
-  "strip",
-  z.ZodTypeAny,
-  {
-    id: number;
-  },
-  {
-    id: number;
-  }
->;
+declare const userSchema: z.ZodObject<{
+  /** The id of the user */
+  id: z.ZodNumber;
+}>;
 type User = z.output<typeof userSchema>;
-declare const authenticatedUserSchema: z.ZodObject<
-  {
-    id: z.ZodNumber;
-    email: z.ZodString;
-  },
-  "strip",
-  z.ZodTypeAny,
-  {
-    id: number;
-    email: string;
-  },
-  {
-    id: number;
-    email: string;
-  }
->;
+declare const authenticatedUserSchema: z.ZodObject<{
+  id: z.ZodNumber;
+  email: z.ZodString;
+}>;
 type AuthenticatedUser = z.output<typeof authenticatedUserSchema>;
 export { userSchema, authenticatedUserSchema, User, AuthenticatedUser };

```

</p>
</details> 

Now look let's see how `authenticatedUserSchema` type is formed.

Zod defines `extend` method as follows:

```ts
extend<Augmentation extends ZodRawShape>(augmentation: Augmentation): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall>;
```

and `objectUntil.extendShape` is already compressed by TypeScript to:

```ts
type objectUtil.extendShape<A, B> = { [k in keyof (Omit<A, keyof B> & B)]: (Omit<A, keyof B> & B)[k]; }
```

We can make the following assumptions traversing it down:

- `T` is the original object we pass to `z.object` in `userSchema` declaration
- `Augmentation` is the object we pass to `extend`
- `UnknownKeys` is in default value, can be omitted
- `Catchall` is in default value, can be omitted
- `objectUtil.extendShape` is simple and can be downcompiled (it is also exported, so if we keep track of exports, we can use it directly as `z.objectUtil.extendShape`, but in this example we assume we don't do that)
- Use of `objectUtil.extendShape` requires `T` and `Augmentation` (**they need to be hoisted**)

Let's hoist types to simple vars:

<details><summary>Patch 2</summary>
<p>

```patch
--- a.d.ts	2023-04-30 22:41:15.311786349 +0000
+++ b.d.ts	2023-04-30 22:41:18.679781850 +0000
@@ -1,9 +1,14 @@
 import { z } from "zod";
-declare const userSchema: z.ZodObject<{
+type _a = {
   /** The id of the user */
   id: z.ZodNumber;
-}>;
+};
+declare const userSchema: z.ZodObject<_a>;
 type User = z.output<typeof userSchema>;
+type _b = {
+  /** The email address of the authenticated user */
+  email: z.ZodString;
+};
 declare const authenticatedUserSchema: z.ZodObject<{
   id: z.ZodNumber;
   email: z.ZodString;

```

</p>
</details>

Now that both types are hoisted, we can compile use of `objectUtil.extendShape`:

<details><summary>Patch 3</summary>
<p>

```patch
--- a.d.ts	2023-04-30 22:43:07.891635955 +0000
+++ b.d.ts	2023-04-30 22:47:20.915298094 +0000
@@ -10,8 +10,7 @@
   email: z.ZodString;
 };
 declare const authenticatedUserSchema: z.ZodObject<{
-  id: z.ZodNumber;
-  email: z.ZodString;
+  [k in keyof (Omit<_a, keyof _b> & _b)]: (Omit<_a, keyof _b> & _b)[k];
 }>;
 type AuthenticatedUser = z.output<typeof authenticatedUserSchema>;
 export { userSchema, authenticatedUserSchema, User, AuthenticatedUser };

```

</p>
</details> 

That's it.

<details><summary>Final declaration</summary>
<p>

```ts
import { z } from "zod";
type _a = {
  /** The id of the user */
  id: z.ZodNumber;
};
declare const userSchema: z.ZodObject<_a>;
type User = z.output<typeof userSchema>;
type _b = {
  /** The email address of the authenticated user */
  email: z.ZodString;
};
declare const authenticatedUserSchema: z.ZodObject<{
  [k in keyof (Omit<_a, keyof _b> & _b)]: (Omit<_a, keyof _b> & _b)[k];
}>;
type AuthenticatedUser = z.output<typeof authenticatedUserSchema>;
export { userSchema, authenticatedUserSchema, User, AuthenticatedUser };

```

</p>
</details> 

And would you look at that, `AuthenticatedUser["id"]` now has description from JSDocs!

## 💻 Use Cases

**What do you want to use this for?**

Preserve JSDocs and make declarations a tiny bit smaller.

**What shortcomings exist with current approaches?**

More computation for TypeScript when reading types because defaults no longer provided (?). Or maybe type mismatch if say Zod in our example updates `ZodObject` type, but I feel like it will break in other way anyway.

**What workarounds are you using in the meantime?**

There is no workaround for that, as far as I am aware.

Well, you can define resulting types by Zod, for example, but then you're losing the beautiful feature of Zod which is type inference, also you put a huge effort into maintaining types. It's not worth it.

## 🎈 Additional context

- While Zod is prelevant here, this issue (request) is not related to Zod, it's just a good example.
- I originally wanted to report that as a bug, but realised this is probably a feature request.
- Real example of this issue: [`@vintl/nuxt` original code](https://github.com/vintl-dev/nuxt/blob/26354bacc9bb7b9c5a22c2c535651ead8ec78b0b/packages/vintl-nuxt/src/module.ts#L31) vs emitted file `dist/module.d.ts` (viewable through [Code tab](https://www.npmjs.com/package/@vintl/nuxt/v/1.1.1?activeTab=code) on npm).