TypeScript-有没有办法将存储在对象中的方法包含到类中?

TypeScript-有没有办法将存储在对象中的方法包含到类中?,typescript,class,Typescript,Class,这是我的代码: // outside class methods function incAge(this: Person) { this.age++; } function changeNick(this: Person, str : string) { this.numberOfNickChanges++; this.nick = str; } // interface IPerson { incAge: () => void; chang

这是我的代码:

// 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
    }
}
public changeNick!: (str : string) => void;
public incAge!: () => void;
我想将这些类外函数
incAge
changeNick
合并到我的类
Person
(IRL函数
incAge
changeNick
将从另一个
.ts
文件导入)

TS警告我,我的函数
incAge
changeNick
没有定义。但是,当我创建此类的新实例时,当
“TS节点”:{“logError”:true}
在我的tsconfig.json中设置时,它可以正常工作


如何删除此错误及其红色扭曲下划线(不在构造函数中使用
this.incAge=incAge.bind(this);
,因为我希望将来包含存储在同一对象中的多个函数?

我已最小化了您的示例,看看这是否适用于您:

想法是,代替
Object.assign(this,{incAge})
,您通过
this.incAge=incAge
显式地为每个函数赋值

//类外方法
职能(本:人){
这个年龄++
}
接口IPerson{
incAge:()=>无效
}
导出类人员实现IPerson{
公众年龄=0
公共收入:()=>无效
构造函数(){
this.incAge=incAge
}
}

最后,我发现我必须替换代码的几个部分:

// 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
    }
}
public changeNick!: (str : string) => void;
public incAge!: () => void;
并调用如下函数:

this.incAge!();