I am trying to run this code but it is giving me following errors:
Animal.ts(10,13): error TS1056: Accessors are only available when targeting ECMAS
Try using tsc myTS.ts --target ES5
this is because TypeScript should Traget ECMA script 5 compiler.
In Windows, the
tsc --target es5 filename.ts
options can be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'esnext'. (without '')
I had the same problem trying to compile TypeScript code with Visual Studio Code. This solved the issue:
1) tsconfig.json - add the target
in the compilerOptions
:
{
"compilerOptions": {
"target": "es5", // <-- here!
"module": "commonjs",
"sourceMap": true
}
}
2) tasks.json - add the target
argument:
{
"version": "2.0.0",
"tasks": [
{
"taskName": "build",
"type": "process",
"command": "tsc",
"args": [
"ts/Program.ts",
"--outDir", "js",
"--sourceMap",
"--watch",
"--target", "es5" // <-- here!
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always"
},
"problemMatcher": "$tsc"
}
]
}
Here you need to pass the switch to type script compiler, so it target ECMAScript file. To do that enter below code in the terminal
tsc (your ts file).ts --target ES5 and run your bulid js file
node (your js file)
Here is a simple solution
tsc file.ts --target ES5 && node file.js
Note: Ensure you make use of your file name. This would only be applicable for you if the name of your .ts file is file.
class AnimalImpm {
constructor(private _name?:string){
this.name = name;
}
get name():string{
return this._name;
}
set name(name:string){
this._name = name;
}
sayName():string {
console.log(`My name is ${this.name}`);
return "Hello";
}
}
let data = new AnimalImpm('Animal');
data.name;
data.name = 'newAnimal';
data.sayName();
In my case, I only needed to add the target.
tsc *.ts --target ES5 && node *.js