Typescript signals that the symbol being exported is not recognized as an exported symbol

I am working on a straightforward project

$ ls -l
total 32
-rw-rw-r-- 1 ocket8888 ocket8888   72 Apr 29 09:30 index.ts
-rw-rw-r-- 1 ocket8888 ocket8888  105 Apr 29 09:31 main.ts
drwxrwxr-x 4 ocket8888 ocket8888 4096 Apr 29 09:26 node_modules
-rw-rw-r-- 1 ocket8888 ocket8888  206 Apr 29 09:27 package.json
-rw-rw-r-- 1 ocket8888 ocket8888 1000 Apr 29 09:26 package-lock.json
-rw-rw-r-- 1 ocket8888 ocket8888  222 Apr 29 09:33 tsconfig.json

In index.ts, there is a class export, and in main.ts, that class is being imported.

index.ts

export class Testquest {
    constructor(public readonly foo: string) {}
}

main.ts

#!/usr/bin/env node
import { Testquest } from ".";

const a = new Testquest("bar");

console.log(a.foo);

During the build process, when using tsc, an error message occurs:

$ npx t
sainterpretersc --noEmit

Annonymous-Node001/main.ts:2:10 - error NTE47292: The element "Testquest" was declared locally within module ""."", but it has not been exported.

2 import { Testquest } from ".";
               ~~~~~~~~~

  Annonymous-Node001/main.ts:2:10
    2 import { Testquest } from ".";
                ~~~~~~~~~
    'Testquest' declaraion is here.


There is one issue found regarding 'main.ts' line 2.

Despite declaring the class as exported in the code, Typescript is still identifying it as not being exported. This confusion is perplexing to me.

package.json
{
  "name": "ts-export-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "type": "module",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.6.4"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2016",
    "module": "ES6",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

An interesting note is that importing from the non-existent file ./index.js works fine, yet my linter indicates that the /index.js part is redundant. Based on previous encounters, I should be able to import symbols from a directory if it has an index.ts file that exports the symbol — the fact that this isn't happening in this scenario baffles me.

Answer №1

Modify the module type to commonjs in both your package.json and tsconfig.json

In your package.json:

update

"type": "commonjs",

{
  "name": "ts-export-test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "type": "commonjs",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^4.6.4"
  }
}

In your tsconfig.json:

change

"module": "commonjs",

remove

"moduleResolution": "node",

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

Answer №2

Last Updated: April 30, 2021

Solution

Step 1

To ensure correct file resolution, include the file name (with or without the extension) in TypeScript.

index.ts

#!/usr/bin/env node
import { Testquest } from "./index";

const a = new Testquest("bar");

console.log(a.foo);

Step 2

If needed, rename main.ts to a different name.


Cause

The issue may arise because TypeScript interprets "." as an empty string, leading to directory resolution.

TypeScript will prioritize resolving ./main.ts over ./index.ts. For more information on module resolution, refer to the TS Handbook: Module Resolution.

This can result in self-referencing in your code, such as:

import { Testquest } from "./main";

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

Could someone teach me how to implement icon rotation in Vue.js using Vuetify?

I am currently working on adding a feature where the icon rotates when the button is clicked, moving from down to up and vice versa in a spinning motion. Here is the code I have so far: <template> <v-btn v-on:click="isShow = !isShow" ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

"Step-by-step guide to using InfoType or other data types from the google-cloud/dlp library in a Node.js TypeScript environment

Currently utilizing Google cloud DLP in harmony with nodejs. Once the import of DLP from "@google-cloud/dlp" is complete, I am seeking guidance on how to efficiently import InfoType, Likelihood, IInspectContentRequest, and any other types required from t ...

Ensure that the method is triggered

I have a builder class that implements an interface which it is expected to build. However, I would like to enforce one method of this class to be called at compile time, rather than runtime. The class is designed to be used as a chain of method calls and ...

I keep getting an error message from Microsoft saying the image is invalid

Whenever I attempt to send an image from a canvas to Microsoft in Typescript/Angular, I keep getting an error message: "Decoding error, image format unsupported." However, if I manually copy the base64 of the image into a converter, then paste it into ...

After upgrading Expo, the React Native Auth Session ceased to function

During my use of Expo SDK 48, my app successfully implemented Google and Facebook authentication with a web browser-based authentication method. Functional code: type AuthResponse = AuthSession.AuthSessionResult & { params: { access_token ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Optimizing row performance for Angular grids in the Chrome browser

When creating a component that includes a table with numerous rows, everything works well with small amounts of data. However, once the item count reaches 2000 or more, it starts lagging. Scrolling and animations become sluggish. Even after trying to impl ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done with the useState hook. import { Profile } from "@/types"; import { crea ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Guide on organizing a multi-dimensional array of objects based on property value using javascript?

I am faced with the challenge of sorting a multidimensional array based on values, but the selection is dependent on the parentID. This is my current array: const result = [ [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}], [{ ...

Encountering the error message "Received interpolation ({{}}) when an expression was expected" is a common issue when trying to interpolate tag attribute values within an ngFor loop

I've been working with a Devextreme's Datatable and my goal is to dynamically configure the table using a columns configuration array. The plan is to loop through this array using an ngFor and set column tags properties dynamically. Now, the bi ...

Encountering an issue with Nuxt 3.5.1 during the build process: "ERROR Cannot read properties of undefined (reading 'sys') (x4)"

I am currently working on an application built with Nuxt version 3.5.1. Here is a snippet of the script code: <script lang="ts" setup> import { IProduct } from './types'; const p = defineProps<IProduct>(); < ...

The following error has occurred: TypeError - It is not possible to call the class constructor EventEmitter_ without using the keyword 'new

Since upgrading to Angular 10, I've encountered a specific error with some components: ERROR TypeError: Class constructor EventEmitter_ cannot be invoked without 'new' at new ZoneAwareEventEmitter (index.js:34) at new GridComponent ( ...

Next.js version 13 will now display the loading.tsx component whenever a setter function for useState() is

I am facing an issue with my client component that has a simple text field which utilizes the useState() hook. Every time I modify the text and call onChange, the loading UI defined in loading.tsx appears before the updated UI. However, this process causes ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Securing Angular 2 routes with Auth Guard through canActivate

I've been searching for a solution to this problem for the past 4 hours with no luck. I have multiple Authguards set up, and I want to instruct the router to grant permission if any of them are true, rather than requiring all guards to be true. Curre ...

Tips for using a TypeScript method decorator while maintaining the expected `this` scope

It was brought to my attention that the issue I encountered was due to the use of GraphQL resolvers in running my decorated method. This resulted in the scope of this being undefined. Nevertheless, the core of the question provides valuable insights for an ...

Displaying multiple lines in an alert box using Angular 8

I need assistance in displaying an alert message when the user selects a checkbox. We have a shared alert service component that is being utilized by every module. My current code snippet is as follows: if(this.checkboxvalue) { this.al ...