Visual Studio Code 'const' 只能在 .ts 文件中使用

Vin*_*dan 14 javascript visual-studio-code

尝试在 Visual Studio Code 中编写基本 JS 时遇到此错误。

已经尝试更改 settings.json ( $workspace/.vscode/settings.json ) 但它不起作用

  {
     "javascript.validate.enable": false
  }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Cla*_*con 12

Afaik,您不能在类声明中定义静态常量。你可以试试这样的

const MAX_WIDTH = 8.5;

class Books {
  get MAX_WIDTH() {
    return MAX_WIDTH;
  }
}

let myBooks = new Books()
alert(myBooks.MAX_WIDTH);
Run Code Online (Sandbox Code Playgroud)


How*_*ard 2

你确定这是正确的 JavaScript 语法吗?

class Books {
    static const MAX_WIDTH = 8.5;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,即使在 ES2015 中也不可能定义静态属性。

您可以尝试其他方法,例如:

class Books {
    static get MAX_WIDTH() {
        return 8.5;
    }
}

console.log(Books.MAX_WIDTH);//8.5
Run Code Online (Sandbox Code Playgroud)