【问题标题】:Why defining object method fails in TypeScript为什么在 TypeScript 中定义对象方法失败
【发布时间】:2017-05-19 21:13:41
【问题描述】:

为什么当我尝试定义对象方法时:

export class Helper {
    function add(x: number, y: number): number {
        return x + y;
    }
}

我收到以下错误:

Unexpected token. A constructor, method, accessor, or property was expected.

我遵循了这个网站的例子:https://www.typescriptlang.org/docs/handbook/functions.html 但是当我删除 function 关键字时它可以工作,但这与官方来源相矛盾。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你不应该在类中使用函数!换成它:

    export class Helper {
        add(x: number, y: number): number {
            return x + y;
        }
    }
    

    Typescript 不允许函数作为类的成员。所以,把它改成一个方法!

    正如 ma​​ttjes 所说,您也可以将方法设为静态...

    export class Helper {
        static add(x: number, y: number): number {
            return x + y;
        }
    }
    
    Helper.add(1,2)
    

    【讨论】:

    • 如果你想要它是静态的,只需将static放在方法声明的前面
    • 不,我不想要静态(类)方法,我想要非静态(对象)方法。
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多