Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program:

function loge(messag){
    console.log(messag);
}

var message:string;

message = "Hi";

loge(message); 

Although I believe there are no syntax errors in my code, I encounter the following error in my Terminal:

SyntaxError: Unexpected token :
  at createScript (vm.js:80:10)
  at Object.runInThisContext (vm.js:139:10)
  at Module._compile (module.js:607:28)
  at Object.Module._extensions..js (module.js:654:10)
  at Module.load (module.js:556:32)
  at tryModuleLoad (module.js:499:12)
  at Function.Module._load (module.js:491:3)
  at Function.Module.runMain (module.js:684:10)
  at startup (bootstrap_node.js:187:16)
  at bootstrap_node.js:608:3

I am puzzled as to why this error occurs and seek assistance to resolve it so I can proceed with my work. My TypeScript version is 2.5.3, and I use PhpStorm as my IDE.

Your help would be greatly appreciated.

Answer №1

After encountering a similar issue, I realized that attempting to compile the .ts file and then directly running the same .ts file using node file_name.ts was causing the problem.

The correct sequence should be to first compile the .ts file using tsc file_name.ts and then execute the generated js file using the command node file_name.js.

Answer №2

Unlike some languages, JavaScript does not support type annotations. This means you should avoid using them like in the following line:

var message:string;

Instead, stick to plain variable declarations without types:

var message

Make sure to transpile your TypeScript code into JavaScript before including the resulting JavaScript file in your application.

Answer №3

I encountered a similar issue recently. It turned out that the mistake I made was attempting to execute the .ts file using node, which is designed for JavaScript files, leading to an error. The correct sequence of actions involves compiling the TS file using the TypeScript compiler (tsc) first and then running it with node. The command should be tsc file.ts followed by node file.js.

Answer №4

To start, you must first convert your typescript code into javascript by transpiling it. Once this is done, you can then utilize the code in your web browser.

Within your project directory, create a file named tsconfig.json with the following contents:

{
  "compilerOptions": {
      "outDir": "./dist/",
      "sourceMap": true,
      "module": "ES6",
      "target": "ES6",
      "baseUrl": "./src/"
  },
  "include": [
      "./src/**/*"
  ]
}

Place your typescript file in the ./src directory and execute the command tsc in your terminal. The transpiled javascript file will be located in the ./dist directory, ready to be used in your browser environment.

Answer №5

It is recommended to execute the JavaScript file instead of the TypeScript file. Use one of the following commands:

  1. npx node dist/script.js or
  2. node dist/script.js

To generate the JavaScript file, run npx tsc -w or tsc -w.
-w signifies a watch mode that updates the JavaScript file when changes are made in the TypeScript file.

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

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Node js - Looping Through Loading

I am facing an issue with my Node.js application. It runs perfectly fine on my local environment, but when I try to run it on my server using forever, the page just keeps loading without displaying anything. There seems to be no response and it gets stuc ...

The conversion from JSON to a PHP API is facing obstacles

I'm having an issue with saving data when a button is clicked using Javascript and PHP. Button click: var xhr = new XMLHttpRequest(); var url = "savedata.php"; xhr.open("POST", url, true); xhr.setReque ...

I am encountering difficulties with hosting a project that was created using Next.js

I am currently working on a Next.js project and I encountered some version compatibility issues when integrating MUI. While my project runs smoothly in localhost, it fails to work when deployed in hosting. I attempted to resolve this by using the --legacy ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

Tips for adding a search bar to a material-ui MenuItem?

Can someone guide me on how to add a search input within the component? I reviewed the material-ui documentation, tried various approaches, but haven't been successful yet. Here's the code for the demo What I attempted: const searchBar = `${& ...

Steps to position images and text side by side in a grid layout

Trying to create a grid layout with profile images and text aligned next to each other, but struggling with CSS. If anyone could provide some guidance, that would be greatly appreciated! Here is the HTML code snippet: <div class="col-sm-3" ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Ajax transmitting data with concealed characters

I'm trying to send data from one PHP site to another. On the first site, everything looks good. The string appears as --show="author,book,text/n However, when I check the string after receiving it on the second site, it shows --show="author,b ...

Using Angular JS, apply multiple column filters within a table to refine the displayed data

I'm currently working on implementing a filter for multiple columns in a table that is being populated by the ng-repeat directive. <tr ng-repeat="descriptiveField in vm.descriptiveFieldList|filter:{name:vm.searchText}" ng-class-even="'even-bg ...

Is it possible to ensure a div occupies all available space within a column using the vh-100 class in bootstrap?

In the <div class="bg-primary"></div> element, I'm trying to make it take up the remaining empty space without exceeding the vh-100. I've experimented with various solutions but haven't been able to find a fix yet. b ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Error encountered following the import from a newly created directory in Angular 2

Recently, I've been working on adding a new folder within my application. Let's assume that I already have components A and B set up. I decided to create a new folder called app/test. Inside this folder, I created a file named test-component.ts ...

Innovative HTML5 Video Canvas Shapes

I'm currently working on creating a circular frame or canvas for live HTML5 Video. While I am able to round the corners using keyframes radius property, it results in an oval shape rather than a circle. My preference would be to utilize a div object ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

Can a new record be created by adding keys and values to an existing record type while also changing the key names?

If I have the following state type, type State = { currentPartnerId: number; currentTime: string; }; I am looking to create a new type with keys like getCurrentPartnerId and values that are functions returning the corresponding key's value in Sta ...

Utilizing AngularJS to incorporate a global scope function within another function

I have a specific AngularJS function named editlocation that triggers a Modal window to edit three data points. Following this process, I aim to execute plotmarkers, which is utilized in another scenario of an ng-click. Despite attempting different approa ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...