如何将自定义类型转换为原始类型? [英] How can I cast custom type to primitive type?
本文介绍了如何将自定义类型转换为原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型
type Rating = 0 | 1 | 2 | 3 | 4 | 5 | number
现在我想做这样的事情。
Now I want to do something like this.
let myRating:Rating = 4
let rate:number = myRating as number
我如何将 myRating
转换为 number
基本类型?
How can I cast my myRating
into number
primitive type?
给我一个错误,为:
It is giving me error as:
将评级类型转换为数字可能是一个错误,因为这两种类型都不足以相互重叠。如果这是故意的,请先将表达式转换为未知。ts(2352)
Conversion of type 'Rating' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.ts(2352)
我已经通过此,但我想要的是相反的
I have been through this, but what I want is its reverse
编辑:
tsconfig.json
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
tsc version: 3.2.1
推荐答案
尝试:
myRating as unknown as number
相同,也请删除 |您的声明中的数字
。
这篇关于如何将自定义类型转换为原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文