“当目标低于 ESNext 时,BigInt 文字不可用”

问题描述 投票:0回答:4

我使用

yarn create react-app my-app --typescript
安装了 React 和 TypeScript。

然后我写了这段代码:

import React from 'react';

const App: React.FC = () => {
  const theBiggestInt = 9007199254740991n;
  return (
    <div>
   {"Durkurian"}
    </div>
  );
}

export default App;

并出现错误:

当目标低于 ESNext 时,BigInt 文字不可用。

问题是什么?我该如何解决它?

package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@types/jest": "24.0.17",
    "@types/node": "12.7.2",
    "@types/react": "16.9.2",
    "@types/react-dom": "16.8.5",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "3.1.1",
    "typescript": "3.5.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
javascript reactjs typescript
4个回答
14
投票

BigInt
node_modules/typescript/lib/lib.es2020.bigint.d.ts
中启用,因此它是
es2020
的一部分,而不是
esnext
的一部分。

但是,

***n
词汇表达式似乎不是
lib.es2020.bigint.d.ts
的一部分。 事实上,这是由
esnext
启用的。

要启用打字稿与

BigInt
但不带
****n
词汇表达式的使用,此配置有效:

{
  "compilerOptions": {
    "lib": [
      "es2020"
    ],
    "module": "commonjs",
    "target": "es2020",
}

将“esnext”添加到库中:

{
  "compilerOptions": {
    "lib": [
      "es2020", "esnext"
    ],
    "module": "commonjs",
    "target": "es2020",
}

然后启用(*)“****n”词汇表达式的能力。

(*) 另一个单独的问题是 VSCode(如果您正在使用它)有时会不透明地启用 '****n' 作为有效表达式,即使相关

tsconfig.json
文件中从未明确提及 'esnext' 时也是如此。 也许它隐式地启用了
esnext
?当尝试确切地确定哪些设置启用
***n
词法表达式时,这种行为实际上没有帮助 - 将
esnext
添加到 tsconfig 文件并 然后将其删除 后,使用
****n
表达式的能力仍然会继续。


3
投票

正如评论中所指出的,Bigint 是一项新功能。当 tsconfig.json 中的目标属性为 ESNext 以外的值时,您不能使用 BigInt。但是您不应该这样做,因为几乎没有浏览器支持开发人员.mozilla.orgcaniuse.com.


0
投票

只需清空 tsconfig.json 并运行构建命令,它就会自动设置正确的配置,也许并不总是如此,但对我有用!如果目标丢失,请添加“target”:“ESNext”!


-1
投票

尝试使用

const theBiggestInt = BigInt(9007199254740991);
代替。我在这里发现了这一点:https://github.com/facebook/create-react-app/issues/6907

9007199254740991n 语法非常新,create-react-app 尚不支持。

编辑:正如下面的评论所指出的,这个答案 BigInt(9007199254740991) 只是 9007199254740991n 的替代语法,所以这对你没有帮助。请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt 了解更多详细信息。

也许尝试使用 https://www.npmjs.com/package/big-integer 代替。当 BigInt 在浏览器中可用时,它会使用 BigInt;当浏览器中不可用时,它会充当 polyfill。

© www.soinside.com 2019 - 2024. All rights reserved.