首页 > 解决方案 > 使用 Create React App 和 TypeScript 在 React 应用程序中出现奇怪的解析错误

问题描述

我正在使用Create React App,最近添加了 TypeScript 支持。

这个代码库开始出现奇怪的问题,使用enum

import React, { useState } from 'react';
import Page from 'components/shared/Page';
import DashboardChart from 'components/shared/DashboardChart';
import { Col, Row, Select, Form } from 'antd';

const { Option } = Select;


enum Periods {
  twentyFourHours = 0,
  oneWeek = 1,
  thirtyDays = 2,
  ninetyDays = 3,
  oneHundredAndEightyDay = 4,
  oneYear = 5
}

我收到此错误:

  Line 9:1:  Parsing error: Unexpected reserved word 'enum'

   7 |
   8 |
>  9 | enum Periods {
     | ^
  10 |   twentyFourHours = 0,
  11 |   oneWeek = 1,
  12 |   thirtyDays = 2,

然后我尝试添加export之前enum

import React, { useState } from 'react';
import Page from 'components/shared/Page';
import DashboardChart from 'components/shared/DashboardChart';
import { Col, Row, Select, Form } from 'antd';

const { Option } = Select;


export enum Periods {
  twentyFourHours = 0,
  oneWeek = 1,
  thirtyDays = 2,
  ninetyDays = 3,
  oneHundredAndEightyDay = 4,
  oneYear = 5
}

这“解决”了这个问题。

如果我在该enum行上方添加评论,我们会遇到另一个问题:

import React, { useState } from 'react';
import Page from 'components/shared/Page';
import DashboardChart from 'components/shared/DashboardChart';
import { Col, Row, Select, Form } from 'antd';

const { Option } = Select;

// export is required here to prevent a syntax error with enum
export enum Periods {

这会导致另一个问题:

  Line 9:13:  Parsing error: Unexpected token

   7 |
   8 | // export is required here to prevent a syntax error with enum
>  9 | export enum Periods {
     |             ^
  10 |   twentyFourHours = 0,
  11 |   oneWeek = 1,
  12 |   thirtyDays = 2,

这是什么法术?我尝试在 VS Code 中使用 Gremlins来发现任何奇怪的字符,但没有运气。

标签: typescriptcompiler-errorscreate-react-app

解决方案


推荐阅读