Is TypeScript inadvertently including unnecessary files in its compilation?

In my configuration file, tsconfig looks like this:

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es6",
    "declaration": true,
    "outDir": "./dist",
  },
  "include": [
    "src/**/*"
  ]
}

Let's consider a simple source file for example:

// ./src/index.ts
function hello() {
  return 'hello';
}

Unexpectedly, an error message pops up:

node_modules/typescript/lib/lib.es2015.iterable.d.ts:41:6 - error TS2300: Duplicate identifier 'IteratorResult'.

41 type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
        ~~~~~~~~~~~~~~

  ../../../node_modules/@types/node/index.d.ts:166:11
    166 interface IteratorResult<T> { }
                  ~~~~~~~~~~~~~~
    'IteratorResult' was also declared here.

The confusion arises as to why it checks

../../../node_modules/@types/node/index.d.ts:166:11
when only src is included?

This issue doesn't occur with the usage of "module": "commonjs".

Answer №1

The issue at hand is that when it comes to the typings, a different rule must be followed compared to the "include" directive. To resolve this, you must incorporate the typeRoots property into your tsconfig compiler options:

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es6",
    "declaration": true,
    "outDir": "./dist",
    "typeRoots": ["./node_modules/@types/"]
  },
  "include": [
    "src/**/*"
  ]
}

If not added, the compiler will search recursively for the types based on the rules outlined here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types

By default, all accessible “@types” packages are included in the compilation process. Packages located in node_modules/@types within any parent folder are considered accessible; which includes packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so forth.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

Create a Jest mock for a namespace and a function that have the same name

The structure of a library I'm currently using is as follows: declare namespace foo { function bar(); }; declare namespace foo.bar { function baz(); }; My task involves mocking the functions foo.bar() and foo.bar.baz(). To mock foo.bar(), ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Customized object property names for an array of generic object types

I am working with an object in Typescript that has a data property structured like this: type MyThing = { data: { options: { myKey: string, myValue: string }[], key: 'myKey', value: 'myValue' } } I want ...

Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something cruc ...

While utilizing Typescript, it is unable to identify changes made to a property by a

Here is a snippet of code I am working with: class A { constructor(private num: number = 1) { } private changeNum() { this.num = Math.random(); } private fn() { if(this.num == 1) { this.changeNum(); if(this.num == 0.5) { ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

Issue with Bot framework (v4) where prompting choice in carousel using HeroCards does not progress to the next step

Implementing HeroCards along with a prompt choice in a carousel is my current challenge. The user should be able to select options displayed as HeroCards, and upon clicking the button on a card, it should move to the next waterfall function. In the bot fr ...

Having trouble achieving success with browser.addcommand() in webdriverIO using typescript

I tried implementing custom commands in TypeScript based on the WebdriverIO documentation, but unfortunately, I wasn't able to get it working. my ts.confg { "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "./*" ], ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date. [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "20 ...

Utilizing TypeScript with Express for dynamic imports

import * as dotenv from 'dotenv'; dotenv.config(); const env: string = process.env.NODE_ENV || 'development'; export const dynamicConfig = async () => { const data = await import('./config.' + env); console.log('d ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

Error message: While running in JEST, the airtable code encountered a TypeError stating that it cannot read the 'bind' property of an

Encountered an error while running my Jest tests where there was an issue with importing Airtable TypeError: Cannot read property 'bind' of undefined > 1 | import AirtableAPI from 'airtable' | ^ at Object.&l ...

The parameter type ‘DocumentData’ cannot be assigned to type ‘never’ in this argument

I've been struggling to find a solution to my issue: Ts gives me an error: Argument of type 'DocumentData' is not assignable to parameter of type 'never' I attempted the solution I found on this page: Argument of type 'Docume ...

Dynamic Assignment of Object Values Based on Enum Keys in Typescript

Check out this TS Playground for this piece of code. Dynamically Assigning Object Values Based on Enum Key I am attempting to achieve the following: in the interface iAnimals, each animal key in the enum Animals should have its associated interface value, ...

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...