Repository: TypeScript
Issue: Range Error: Maximum call stack size exceeded while compiling our code
Labels: Needs Investigation,Fix Available,Rescheduled

# Bug Report

<!--
  Please fill in each section completely. Thank you!
-->

### 🔎 Search Terms

<!--
  What search terms did you use when trying to find an existing bug report?
  List them here so people in the future can find this one more easily.
-->

tsc: RangeError: Maximum call stack size exceeded 

### 🕗 Version & Regression Information

<!-- When did you start seeing this bug occur?

"Bugs" that have existed in TS for a long time are very likely to be FAQs; refer to
  https://github.com/Microsoft/TypeScript/wiki/FAQ#common-bugs-that-arent-bugs

If possible, please try testing the nightly version of TS to see if it's already been fixed.
For npm: `typescript@next`
This is also the 'Nightly' version in the playground: http://www.typescriptlang.org/play/?ts=Nightly

Note: The TypeScript Playground can be used to try older versions of TypeScript.

Please keep and fill in the line that best applies:
-->
- This is a compilation error, that happened in typescript 4.6.4.

### ⏯ Playground Link
https://github.com/Klab-Berlin/mongoose-test

### 💻 Code

<!-- Please post the relevant code sample here as well-->

```
import mongoose from 'mongoose';

export type Schema<T> = {
  [key in keyof T]: TypeSchema<T[key]>
};

type TypeSchema<T> =
  T extends { type: (typeof mongoose.Schema.Types.String)[] } ? string[] :
  T extends { type: typeof mongoose.Schema.Types.String } ? string :
  T extends { type: (typeof mongoose.Schema.Types.Number)[] } ? number[] :
  T extends { type: typeof mongoose.Schema.Types.Number } ? number :
  T extends { type: (typeof mongoose.Schema.Types.Boolean)[] } ? boolean[] :
  T extends { type: typeof mongoose.Schema.Types.Boolean } ? boolean :
  T extends { type: any[] } ? any[] :
  T extends { type: any } ? any :
  Schema<T>;

/**
 * @template {mongoose.SchemaDefinition} T
 * @param {T} schemaBody
 * @param {mongoose.SchemaOptions} [options = {}]
 * @returns {import('./schema').Schema<T>}
 */
function createSchema(schemaBody, options = {}) {
  // @ts-ignore
  return new mongoose.Schema(schemaBody, options);
}


const { String, Number, Boolean, ObjectId, Mixed } = mongoose.Schema.Types;

export const userSchema = {
  someList: [
    createSchema(
      {
        id: { type: Number },
        paths: [
          createSchema(
            { path: { type: String }, type: { type: String } },
            { _id: false, id: false },
          ),
        ],
      },
      { _id: false, id: false },
    ),
  ],
};
```
tsconfig.json
```
{
  "compilerOptions": {
    "target": "es2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "lib": ["es6"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    "module": "commonjs", /* Specify what module code is generated. */
    "rootDir": "src", /* Specify the root folder within your source files. */
    "resolveJsonModule": true, /* Enable importing .json files */
    "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    "checkJs": false, /* Enable error reporting in type-checked JavaScript files. */
    "outDir": "build/server", /* Specify an output folder for all emitted files. */
    "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
    "strict": true, /* Enable all strict type-checking options. */
    "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    "skipLibCheck": true, /* Skip type checking all .d.ts files. */
    "removeComments": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build/**/*"]
}

```

```ts
// We can quickly address your report if:
//  - The code sample is short. Nearly all TypeScript bugs can be demonstrated in 20-30 lines of code!
//  - It doesn't use external libraries. These are often issues with the type definitions rather than TypeScript bugs.
//  - The incorrectness of the behavior is readily apparent from reading the sample.
// Reports are slower to investigate if:
//  - We have to pare too much extraneous code.
//  - We have to clone a large repo and validate that the problem isn't elsewhere.
//  - The sample is confusing or doesn't clearly demonstrate what's wrong.
```

### 🙁 Actual behavior

<!-- What happened, and why it was wrong -->
When we try to compile our code with tsc and with the given tsconfig file, we get the error `tsc: RangeError: Maximum call stack size exceeded`.

The whole error log:
```
running better-npm-run in $PROJECT_ROOT
Executing script: server:build

to be executed: tsc 
/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:95302
                throw e;
                ^

RangeError: Maximum call stack size exceeded
    at instantiateTypes (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51421:34)
    at getObjectTypeInstantiation (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51557:80)
    at instantiateTypeWorker (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51757:28)
    at instantiateTypeWithAlias (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51737:26)
    at instantiateType (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51723:37)
    at getConditionalType (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:50792:35)
    at getConditionalTypeInstantiation (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51715:25)
    at instantiateTypeWorker (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51789:24)
    at instantiateTypeWithAlias (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51737:26)
    at instantiateType (/$PROJECT_ROOT/node_modules/typescript/lib/tsc.js:51723:37)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! api@0.0.1 server:build: `bnr server:build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the api@0.0.1 server:build script.
```

### 🙂 Expected behavior

<!-- What you expected to happen instead, and why -->
We expect to be able to compile this code. Not really sure if there is a problem with out types.