typescript - 意外的标记;预期 'constructor、function、accessor 或 variable'
抱歉问一个新手问题,但我正在尝试学习 TypeScript。
我有以下类
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 上遇到错误。错误是“意外的标记;预计是 '构造函数、函数、访问器或变量'。”
我哪里做错了?
一过性脑缺血发作
答案#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);
};
}
我还对你代码中的其他问题进行了修复,见我提供的代码中:
blocksPerRow和blocksPerColumn未定义。使用this.。它是一个函数,所以调用它(123)。- 如果你打算使用
=,更推荐使用arrow()=>而不是function(更多内容 https://www.youtube.com/watch?v=tvocUcbCupA)
