A sample project in typescript and vscode (Windows 11)
This is my app.ts
code
function add(n1: number, n2:number) {
return n1 n2;
}
const number1 = 5;
const number2 = 2.8;
const result = add(number1, number2);
console.log(result);
evrything compiles with no errors
But when I click on Run|Run Without Debbugging, I get this error
Uncaught SyntaxError g:\TypeScript\TS_4\2_Types\010_basics-1\app.ts:2
function add(n1: number, n2:number) {
^
SyntaxError: Unexpected token ':'
at compileFunction (undefined:352:18)
at wrapSafe (undefined:1033:15)
at Module._compile (undefined:1069:27)
at Module._extensions..js (undefined:1159:10)
at Module.load (undefined:981:32)
at Module._load (undefined:822:12)
at executeUserEntryPoint (undefined:77:12)
at <anonymous> (undefined:17:47)
This my index.html
file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Understanding TypeScript</title>
<script src="app.js" defer></script>
</head>
<body>
</body>
</html>
when I run the html file, there is no bug, abd the expected result apperas in the console
CodePudding user response:
You can't just run a TS file.
The error you are getting is because a TS file is not a valid JS file because of the type definitions !
Make sure you follow the procedure described here:
Define a .tsconfig
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "out",
"sourceMap": true
}
}
and setup your launch.json
:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/helloworld.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/out/**/*.js"]
}
]
}
CodePudding user response:
You need a space between n2
and number
?
I strongly suggest you to get full support from the editor while coding.