I'm trying to create a class in TypeScript, where I initialise a property / field in a class. But whenever I compile this to JS using tsc and try to initialise this class, I always get an error.
class Component {
type_: string;
constructor(type_: string) {
this.type_ = type_;
}
getDefinition(): Object {
return {
type: this.type_
};
};
}
export { Component };
Error:
this.type_ = type_;
^
TypeError: Cannot set property 'type_' of undefined
at Component (/Users/GitHub/ts-module/lib/components/base.js:6:20)
at Object.<anonymous> (/Users/GitHub/ts-module/test.js:3:1)
at Module._compile (internal/modules/cjs/loader.js:1200:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Offending code:
const base = require('./lib/components/base');
const { Component } = base;
Component("Section");
This is literally the most basic example from the TS docs so I cannot for the life of me figure what I'm doing wrong...
As commented above, I needed to do new Component(...) instead. I'd have thought it would have given me an error instead...