Is there a way for TS-Node to utilize type definitions from the `vite-env.d.ts` file?

I am utilizing Mocha/Chai with TS-Node to conduct unit tests on a React/TypeScript application developed with Vite.

While most tests are running smoothly, I am encountering difficulties with tests that require access to type definitions from vite-env.d.ts. The challenge lies in referencing these types for TypeScript to recognize when working through TS-Node.

Directory structure:

myProject/
  src/
    ts/
      myModule.ts
    vite-env.d.ts
  test/
    unit/
      myModule.spec.ts
    .mocharc.json
    tsconfig.json
package.json

Configuration files:

// package.json
{
  "type": "module",
  "scripts": {
    "test": "mocha --config test/.mocharc.json"
  },
  "devDependencies": {
    "@types/chai": "^4.3.4",
    "@types/mocha": "^10.0.1",
    "chai": "^4.3.7",
    "mocha": "^10.2.0",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.3",
    "vite": "^4.0.0"
  }
}
// test/.mocharc.json
{
  "loader": "ts-node/esm",
  "extensions": [
    "ts"
  ],
  "spec": [
    "test/**/*.spec.ts"
  ],
  "watch-files": [
    "src/vite-env.d.ts",
    "src/ts/*.ts",
    "test/**/*.spec.ts"
  ],
  "experimental-json-modules": true
}
// test/tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext"
  },
  "ts-node": {
    "esm": true
  }
}

Vite type definitions:

// src/vite-env.d.ts
/// <reference types='vite/client' />

type MyCustomType= {
  start: string,
  end: string
};

Module under testing:

// src/ts/myModule.ts
function foo({ start, end }: MyCustomType): string {
   // ...
}

export { foo };

Test file:

// test/unit/myModule.spec.ts
import 'mocha';
import { expect } from 'chai';
import { foo } from '../../src/ts/myModule.js';

describe("foo is awesome", () => {
  it("works! :D", () => {
    const bar = foo({ start: "", end: ""});
    expect(bar).to.be.string;
  });
});

Current error:

TSError: ⨯ Unable to compile TypeScript:
src/ts/myModule.ts:2:30 - error TS2304: Cannot find name 'MyCustomType'.

2 function foo({ start, end }: MyCustomType): string {

...

Adding the MyCustomType definition directly into myModule.ts resolves the issue. However, this approach would be cumbersome for numerous files that share the same type definitions.

Including "types": [ "src/vite-env.d.ts" ] in the compilerOptions does not seem to make any difference.

What steps can be taken to enable TS-Node to utilize the type definitions from vite-env.d.ts?

Answer №1

Make sure to include the following code in your tsconfig.json file:

{
  "compilerOptions": {
    "types": ["path/to/d.ts", "node"]
  },
  "include": ["**/*.ts"]
}

Additionally, ensure that your tsconfig.json is located at the root of your project along with the package.json file.

Answer №2

{
  "files": [
    "./vite-env.d.ts"
  ],
  "compilerOptions": {
  
  },
  "ts-node": {
    "files": true
  }
}

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

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

Error encountered when using a connected component in Typescript with Redux

Seeking assistance on integrating state from redux into properties within a react component that is outlined in a tsx file. The LoggedInUserState type has been defined elsewhere and is exported as shown below: import { Action, Reducer } from 'redux& ...

Exploring the functionality of CanDeactiveGuard and ModalDialogService through unit testing

In my application, the CanDeactiveGuard is functioning properly. During unit testing, I encountered an issue with one test where I intended to use callThrough to invoke the openConfirmDialog() method within the Guard. This method triggers the Modal Dialog ...

Encountering an issue while attempting to initiate a nested array: "Cannot assign a value to an optional property access in the left-hand side of an assignment expression."

I am dealing with an object that contains nested arrays, structured like this: export class OrdenCompra { public id?: number, public insumos?: OrdenCompraInsumo[], } export class OrdenCompraInsumo { id?: number; traslados?: IImpuestoTraslado[]; } export ...

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

Displaying nested objects within an object using React

Behold this interesting item: const [object, setObject] = useState ({ item1: "Greetings, World!", item2: "Salutations!", }); I aim to retrieve all the children from it. I have a snippet of code here, but for some reason, i ...

The program encountered an error with code TS2339, indicating that the property "name" cannot be found on the type "never"

app.component.html I'm attempting to display the response data from my Firebase project using *ngFor. <div class="row"> <div class="col-md-3"> <h4 class="text-warning">All Employee Da ...

Contrasting Dependency Injection with Exporting Class Instances

I've been diving into the world of TypeScript and working on enhancing my skills as a web developer. One project I'm currently focused on is a simple ToDo app, which you can find here: https://github.com/ludersGabriel/toDo/tree/dev/backend. My q ...

Utilizing UI-GRID to showcase JSON information

I am currently in the process of fetching data from the server. [ { id:1, name:demo, request: { id: 1, localCompany: { id: 1 } } }] [{ }, { }] This is how my JSON object appears to be structured. After calling ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

Encountering ng build --prod errors following Angular2 to Angular4 upgrade

Upon completing the upgrade of my Angular2 project to Angular4 by executing the following command: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @an ...

Tips on setting up an npm package for automatic updates

I recently created a package called https://www.npmjs.com/package/nestjs-notifications After running npm install nestjs-notifications --save, I noticed that it installed successfully but saved the version as: "nestjs-notifications": "0.0.10 ...

Printing using *ngFor will display items in an ascending order

When attempting to display an object in markup, I am running into the issue of *ng printing it in ascending order instead of maintaining the original order. Ideally, I would like the elements to be printed as they are. You can view my code on StackBlitz ...

What is the best way to deliver a downloaded document to a client using NodeJS Express?

I am facing an issue with downloading files from my FTP server using a button on my front-end website. The FTP server is password protected, and only I as the admin have access to the password. However, when the user clicks the download button, the file ge ...

Guide on accomplishing masking in Angular 5

I'm curious if it's achievable to design a mask in Angular 5 that appears as follows: XXX-XX-1234 Moreover, when the user interacts with the text box by clicking on it, the format should transform into: 1234121234 Appreciate your help! ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

Error 2322: Troubleshooting Typescript arrow functions overloads issues

Everything seems to be working well with the code below, except for an error that occurs with the resolve constant. const resolve: Resolve Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | ...

Using Typescript, invoke functions within an object by specifying a string key

I am looking for a way to call methods in an Object using string keys, but I'm facing issues with it. Could someone provide some solutions for this? type Methods = { foo?: (v: string) => string; bar?: (v: number) => number; baz?: (v ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...