justcodin
justcodin

Reputation: 1013

TypeScript - Is there a way to include methods stored in a object into a class?

This is my code :

// 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 these outside class functions incAge and changeNick that I wanted to incorporate into my class Person (IRL functions incAge and changeNick will be imported from another .ts file)

TS warns me that my functions incAge and changeNick are not defined however, when I create a new instance of this class, it works without a problem when "ts-node": { "logError": true } is set in my tsconfig.json.

How can I remove this error and its red squiggly underline (without using this.incAge = incAge.bind(this); in the constructor because I would like to include multiple functions that are stored in the same object in the future ?

Upvotes: 0

Views: 33

Answers (2)

justcodin
justcodin

Reputation: 1013

Finally, I founded that I must replace several parts of my code :

public changeNick!: (str : string) => void;
public incAge!: () => void;

and call function like this :

this.incAge!(); 

Upvotes: 0

Pritam Kadam
Pritam Kadam

Reputation: 2527

I have minimised your example, see if this works for you:

Idea is, instead of Object.assign(this, { incAge }), you assign value to each function explicitly by this.incAge = incAge

// outside class methods
function incAge(this: Person) {
  this.age++
}

interface IPerson {
  incAge: () => void
}

export class Person implements IPerson {
  public age = 0
  public incAge: () => void

  constructor() {
    this.incAge = incAge
  }
}

Upvotes: 1

Related Questions