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

Stop MatDialog from closing automatically when clicked outside while there are unsaved changes

Is there a way to prevent closing when there are pending changes without success? this.dialogRef.beforeClosed().subscribe(() => { this.dialogRef.close(false); //some code logic //... }); The setting disableClose on MatDialog must remain as false ...

Comparison between WAMP and Live server integration with Facebook for connecting applications

I've been facing some challenges while integrating my website with Facebook Connect. I have been following the instructions provided in this guide. When attempting to run the following code from localhost, please note that for security reasons, my ap ...

Trouble arises when trying to test an Angular service that relies on abstract class dependencies

Currently, I am working on a service that has a dependency on another service, which in turn relies on two abstract classes as dependencies. (ThemeConfigService -> (SettingsService -> SettingsLoader, NavigationLoader)) During testing, the failure oc ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

What is the best way to repair a react filter?

Recently, I successfully created a database in Firebase and managed to fetch it in React. However, my current challenge is to integrate a search bar for filtering elements. The issue arises when I search for an element - everything functions as expected. ...

Troubleshooting a malfunctioning ember.js HTML output

I'm currently facing a challenging debugging task to figure out why this specific code snippet is failing: Here is the template causing issues: <p class='navbar-text pull-right header-user-info'> {{#if currentUser.isSignedIn}} {{#i ...

How to incorporate a JavaScript class into a VueJS project

Looking to incorporate a JavaScript class into my Vue application. The class structure is as follows: class className { constructor() { ... } function1() { ... } static funtion2() { ... } } Attemptin ...

Is it necessary to publish a package for client-side usage on npm?

I'm struggling to understand the recent trend of using npm to publish client-side packages that have no dependencies. Take for example a simple class that extends HTMLElement and can only be used in the browser by adding a script tag to an HTML file. ...

"I am eager to showcase the text upon pressing the Enter key, implementing an Immediately Invoked Function Expression

My input text box is supposed to store and display the output in an unordered list format when I hit enter. The function works fine without IIFE using onclick event, but it's not working with IIFE. Can anyone assist me with this issue? <html> ...

Issues with AJAX formData functionality

I'm having difficulties with the formData in my Ajax calls. I have searched extensively for solutions and tried various approaches, including using getElementById, but nothing seems to work. The form in question has an id of add-lang-form: <form ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Iterating through a nested array in order to dynamically generate elements using JavaScript/jQuery

Seeking assistance with a specific issue I am facing. Despite extensive research on this platform, I have not found a solution to my problem. Recently, I successfully used jQuery each to loop over objects. However, I am currently struggling to iterate thro ...

Guide on assigning a material to ColladaLoader or OBJLoader

I've searched extensively through the documentation and numerous examples, but I couldn't find the correct syntax for assigning a material to either a Collada .dae or OBJLoader .obj file. Json files seem to work well when creating a Mesh, with t ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Do these exports serve the same purpose?

Can someone help me understand why one export works while the other doesn't? I've tried to figure it out on my own but I'm stuck. Functioning Example const dataStore = new Vapi({ baseURL: 'http://domain.test/api', state: ...

What is the reason for needing to specify event.target as an HTMLInputElement?

I am currently working on a codebase that uses Material Ui with theme overrides. As I set up my SettingContext and SettingsProvider, I find myself facing some syntax that is still unclear to me. Let's take a look at the following code snippet: const ...

What is the reason for including parentheses when evaluating JSON data?

What is the purpose of adding ( and ) around the code when using eval? var strJson = eval("(" + $("#status").val().replace(";","") + ")"); Note: The result of $("#status").val() is similar to {"10000048":"1","25000175":"2","25000268":"3"}; ...

"Add a hover effect to fade the image and make it clickable for a

Is there a way to make the entire image a clickable link when it's hovered over, rather than just the text inside? I could use some assistance with this. Javascript: $('.thumbnail').hover(function() { $('.thumbnail img').stop ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...