Javascript TypeScript 意外标记,需要构造函数、方法、访问器或属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43070702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:39:43  来源:igfitidea点击:

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

javascripttypescriptecmascript-6es6-class

提问by Guido Kleijer

Just trying to write a function within a class using typescript.

只是尝试使用打字稿在类中编写函数。

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

This results in the following error:

这会导致以下错误:

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

TypeScript 意外标记,需要构造函数、方法、访问器或属性。

I copied the example from: https://www.typescriptlang.org/docs/handbook/functions.html

我从以下位置复制了示例:https: //www.typescriptlang.org/docs/handbook/functions.html

Am I missing something? I'm confused!

我错过了什么吗?我糊涂了!

回答by Mike Chamberlain

You shouldn't use the functionkeyword in a Typescript class definition. Try this instead:

您不应function在 Typescript 类定义中使用关键字。试试这个:

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

回答by Matthew Layton

TypeScript does not allow functiondeclarations as class members; it has a slightly different syntax for that...

TypeScript 不允许function声明为类成员;它的语法略有不同......

class Test 
{
    // This will bind the add method to Test.prototype
    add(x: number, y: number): number 
    {
        return x + y;
    }

    // This will create a closure based method within the Test class
    add2 = (x: number, y: number) => {
        return x + y;
    }
}