Reputation: 6265
I currently have a typescript class that sets class values in a constructor. I then reference these values using "this" in a class method. The .ts file compiles fine without warnings. However, when I import the compiled .js file in another project, if I call the class method I get an error that this is undefined.
I have a few tests written for the file in typescript, and they all work fine.
Here's a simplified example.
# class .ts file
export class MyClass {
public myValue: number;
constructor(val: number) {
this.myValue = val;
}
logValue() {
console.log(this);
console.log(this.myValue);
}
}
# regular js project importing built .js file
import { MyClass } from 'myProject'
const x = new MyClass(5);
x.logValue(); // error, cannot read property myValue of undefined, first console.log logs 'undefined';
here's my tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
// useTypeInferenceAsMuchAsPossible
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outDir": "./lib",
"allowJs": true,
"target": "es5",
"lib": [
"es7",
"es2015.symbol",
"es2015.symbol.wellknown"
]
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
Thanks!
Upvotes: 1
Views: 55
Reputation: 276115
This code actually does not error:
const x = new MyClass(5);
x.logValue();
However this will error:
const x = new MyClass(5);
const logValue = x.logValue;
logValue(); // Error
It is simply because of how this
works.
You can use an arrow function. Change:
logValue() {
console.log(this);
console.log(this.myValue);
}
To :
logValue = () => {
console.log(this);
console.log(this.myValue);
}
Upvotes: 4