首页 > 解决方案 > 如何在 Typescript 中转换类的方法

问题描述

我的目标是能够在不重复参数类型和返回类型的情况下声明一个方法。我为此使用了打字稿Type

但是现在,如何告诉 Typescriptheyy Typescript, this method sum is of type IBar

type IBar = (x:number, y: number)=>number;
class Foo {
    sum(x,y){
        return x+y;
    } as IBar
}

我试过了

type IBar = (x:number, y: number)=>number;
class Foo {
    sum:IBar=(x,y)=>{
        return x+y;
    }
}

但不幸的是,这将 javascript 代码转换为:

class Foo {
    constructor() {
        this.sum = (x, y) => {
            return x + y;
        };
    }
}

我正在寻找可以转换为:

class Foo {
    sum(x, y) {
        return x + y;
    }
}

标签: javascripttypescripttypes

解决方案


推荐阅读