Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code:

interface TestInterface {
    id: number;
    text: string;
}

const testInterfaceImplementation: TestInterface = {
    id: 1,
    text: 'sample text'
};

console.log(testInterfaceImplementation.text);

However, when I try to run this code using Node.js configuration, I encounter the following error message:

interface TestInterface {
          ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

If I remove the interface from the code, it runs without any errors:

const testInterfaceImplementation = {
    id: 1,
    text: 'sample text'
};

console.log(testInterfaceImplementation.text);

What could be causing this issue? I have even attempted moving the interface to a separate .ts file, but the error persists.

This is my tsconfig.json file:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

run_configuration

Answer №1

In order to execute Typescript code with Node.js, you cannot do so directly as Node.js does not have native support for it. The code must either be compiled on-the-fly or precompiled. Here are some methods:

To run a specific TypeScript file using ts-node:

  • First, install ts-node by running npm i ts-node.
  • Create a new configuration for running/debugging in Node.js.
  • Add --require ts-node/register to the Node parameters field.
  • In the JavaScript file field, add $FilePathRelativeToProjectRoot$.
  • Save the configuration settings.
  • Execute this configuration to run (or debug) a file that is currently open or selected in the Project view.

If you need to include additional parameters for ts-node (e.g., --project tsconfig.json), you can add them to the Application parameters field in the configuration.

To compile an application with TypeScript and run a selected TypeScript file

  • Set up a new run/debug configuration in Node.js.
  • In the Before Launch section, click Add and choose Compile TypeScript.
  • Select the tsconfig.json file.
  • In the JavaScript file field, specify the path to the compiled .js file.
  • If the compiled JavaScript file is located next to its source, add
    $FileRelativeDir$/$FileNameWithoutExtension$.js
  • If the files are saved in an output folder without changing their structure, add the folder name before the pattern, e.g.,
    build/$FileRelativeDir$/$FileNameWithoutExtension$.js
  • Save the configuration settings.
  • Execute this configuration to run (or debug) a file that is currently open or selected in the Project view.

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

Ensuring the authenticity of a Node.js model through the utilization of

Recently, I've been working on developing a NodeJS application using JavaScript and MySQL. As the object I'm handling started to grow in complexity making it difficult to read, I received a recommendation to implement the builder pattern. In resp ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

When the click event is triggered, the second function guess() does not execute

I am currently developing a number guessing application. It consists of two functions, the first one called startGame() works correctly (it receives the maximum number and then disappears by adding the hidden class). However, the second function that is ...

Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links). I've tried various methods, but the current jQuery method I'm using ad ...

The code functions properly on a standalone device, however, it encounters issues when

I am facing an issue with my JavaScript code. It works perfectly fine when I run it on my local machine, but once I upload it to the server, it only functions properly after I refresh the page. Below is the code in question. Please do not hesitate to rea ...

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

What is the best way to make a JSONP request using jQuery?

Whenever I try to access this API through the browser, everything works fine and I receive the correct response. However, when I attempt to call the API using jQuery AJAX, I encounter an error. *The script is being refused execution from 'http://api ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Managing dependencies with Yarn or npm

While experimenting with remix and mui v5, I encountered some issues. When using npm and running npm run dev, I received the following error: Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supporte ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...

What is the best way to incorporate custom events into classes using Node.js?

Recently delving into node, I have a question about adding custom events to a class. In the code below, I attempted to create a simple farm class where the number of animals changes and triggers an event called totalChanged. let events = require('eve ...

Prevent infinite scrolling with JavaScript AJAX when the response is empty

I am currently implementing the infinite scroll functionality on my website. Whenever the page reaches the bottom, an ajax call is triggered to fetch a new set of data. However, I'm unsure how to handle stopping the ajax call if there is no more data ...

Linking to a Different Tab without Tab Mutation with Bootstrap 3.3.5

I am facing a similar issue to the mentioned questions. I am trying to use a link to change tabs, but the problem is that the link only changes the tab content and not the active tab. The most similar question can be found at: Bootstrap linking to a tab w ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

The background gently fades away, directing all attention to the popup form/element

After extensive searching, I have yet to find a straightforward solution that seems to be a standard practice on the web. My goal is to create a form that appears in the center of the screen when a button is clicked using CSS or jQuery. I would like the ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...