【发布时间】:2019-05-17 16:47:47
【问题描述】:
我有一个类型
type Rating = 0 | 1 | 2 | 3 | 4 | 5 | number
现在我想做这样的事情。
let myRating:Rating = 4
let rate:number = myRating as number
如何将我的 myRating 转换为 number 原始类型?
它给我的错误是:
类型 'Rating' 到类型 'number' 的转换可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请将表达式转换为 'unknown' first.ts(2352)
我已经通过this,但我想要的是它的反向
编辑:
tsconfig.json
{
"compilerOptions": {
"noImplicitAny": false,
"target": "es6",
"allowJs": true,
"skipLibCheck": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"strict": true
},
"include": [
"src"
]
}
tsc 版本:3.2.1
【问题讨论】:
-
您使用的是哪个打字稿版本?另外,请分享您的 tsconfig 文件,因为您的代码使用
typescript@3.2.2为我编译而没有错误 -
@NitzanTomer 我已经更新了我的问题
-
对不起,如果你在你的类型
Rating中包含类型number,为什么还要费心把数字列表放在0-5之间呢? -
它成功了,这是因为库 Rating 和我的类型名称 Rating 之间的名称冲突,我将我的类型重命名为 RatingType 并且它有效。
-
我无法重现这个,使用你的 tsconfig 它编译得很好。
标签: javascript typescript types casting