【问题标题】:String Enum in typescript error打字稿错误中的字符串枚举
【发布时间】:2017-10-30 12:09:58
【问题描述】:

我尝试将字符串枚举添加到我的 Angular 2 项目中,但在使用 npm 启动项目时出错:

ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m
odels/enums/Sex.ts (2,10): Type '"Male"' is not assignable to type 'Sex'.
ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m
odels/enums/Sex.ts (3,12): Type '"Female"' is not assignable to type 'Sex'.
ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m
odels/enums/Sex.ts (4,8): Type '"NA"' is not assignable to type 'Sex'. 

枚举声明:

export enum Sex {
  Male = 'Male',
  Female = 'Female',
  NA = 'NA'
}

和打字稿版本:

e:\projects\dbtool-fullstack\dbtool-client>tsc --version
Version 2.5.3

e:\projects\dbtool-fullstack\dbtool-client>npm list -g --depth=0
C:\Users\pavlo\AppData\Roaming\npm
+-- @angular/cli@1.4.4
+-- npm@5.5.1
`-- typescript@2.5.3

这种类型的枚举声明应该从版本 2.4.0 开始工作

这是什么原因造成的?

更新

当我使用 ng -v 时:

e:\projects\TESTENUMS>ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.4.9
node: 6.11.3
os: win32 ia32
@angular/animations: 4.4.6
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.9
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.3.4

在这种情况下,TS 的版本是 2.3.4。我不知道它是从哪里来的。

【问题讨论】:

标签: node.js angular typescript npm enums


【解决方案1】:

重要

事实证明,当前版本的 Angular (4.4.6) 不支持 Typescript >=2.4.0。应该从 v5.0.0 开始支持,目前还没有。

更改项目打字稿版本的操作:

  1. 需要在 package.json 中设置正确的 typescript 版本(在我的例子中是 2.5.3)。
  2. 在项目根目录(包含 package.json 的文件夹)中运行 nmp install,之后应该可以工作了。
  3. 为确保使用正确的打字稿版本,请运行ng -v

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2020-07-11
    • 2021-04-19
    • 2020-04-30
    • 1970-01-01
    • 2019-10-30
    相关资源
    最近更新 更多