This is the code snippet I am working with:
// These are the outside class methods
function incAge(this: Person) {
this.age++;
}
function changeNick(this: Person, str : string) {
this.numberOfNickChanges++;
this.nick = str;
}
//
interface IPerson {
incAge: () => void;
changeNick: (str : string) => void;
nick : string;
numberOfNameChanges : number;
}
export class Person implements IPerson {
public nick: string = "no name";
public age: number = 0;
public age: numberOfNickChanges = 0;
public changeNick: (str : string) => void;
public incAge: () => void; // Warning : Property 'incAge' has no initializer and is not definitely assigned in the constructor.ts(2564)
constructor() {
Object.assign(this, { incAge, changeNick });
this.incAge(); // Warning : Property 'incAge' is used before being assigned.ts(2565)
console.log(this.age); // prints 1
}
}
I have defined external functions incAge
and changeNick
that I want to integrate into my Person
class. When I create a new instance of the class, it works fine despite TypeScript warning me that the functions are undefined. Setting
"ts-node": { "logError": true }
in my tsconfig.json resolves the issue.
How can I address this error without using this.incAge = incAge.bind(this);
in the constructor, as I plan to include multiple functions stored in the same object in the future?