【问题标题】:Unexpected token; 'constructor, function, accessor or variable' expected意外的标记; '构造函数、函数、访问器或变量'预期
【发布时间】:2015-10-02 10:57:42
【问题描述】:

很抱歉这个新手问题,但我正在尝试学习类型脚本。

我有以下课程

class indexGridFunctions
{

    //Error on the var
    var blocksPerRow: (windowWidth:number)=>number
    = function (windowWidth)
    {
        return Math.floor(windowWidth / 12);
    };

    var blocksPerColumn: (windowHeight: number) => number
    = function (windowHeight)
    {
        return Math.floor(windowHeight / 17);
    };

    shirtsToDisplay: () => number
    = function ()
    {
        return blocksPerRow * blocksPerColumn;
    };

} 

我在第一个 var 处遇到错误。错误是“意外的令牌;需要'构造函数、函数、访问器或变量'”。

我做错了什么?

TIA

【问题讨论】:

    标签: typescript


    【解决方案1】:

    不要使用var。它在类体内的无效语法。固定代码:

    class indexGridFunctions {
    
        blocksPerRow: (windowWidth: number) => number
        = function (windowWidth) {
            return Math.floor(windowWidth / 12);
        };
    
        blocksPerColumn: (windowHeight: number) => number
        = function (windowHeight) {
            return Math.floor(windowHeight / 17);
        };
    
        shirtsToDisplay: () => number
        =  () => {
            return this.blocksPerRow(123) * this.blocksPerColumn(123);
        };
    
    } 
    

    我还在我提供的代码中对您的代码进行了其他修复:

    • blocksPerRowblocksPerColumn 未定义。使用this.。它是一个函数,所以称之为(123)
    • 如果你打算使用=(更多https://www.youtube.com/watch?v=tvocUcbCupA),首选arrow ()=>而不是function

    【讨论】:

    • 非常感谢。我已经重写了几十次尝试不同的变化。这个。是我原始代码库中缺少的东西。非常感谢您帮助新手。我还将您的其他建议添加到我的代码中。
    • 请注意,所有这些都是 TypeScript 编译器在编译时指出的 ;)
    猜你喜欢
    • 2017-03-22
    • 2016-09-12
    • 2016-03-30
    • 1970-01-01
    • 2018-07-07
    • 2011-12-04
    • 2010-12-12
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多