如何将自定义类型转换为基元类型?

我有喜欢的类型

type Rating = 0 | 1 | 2 | 3 | 4 | 5 | number

现在我想做这样的事情。

let myRating:Rating = 4
let rate:number = myRating as number

如何将 myRating转换为 number基元类型?

它给我带来的错误是:

将类型“ Rating”转换为类型“ number”可能是一个错误,因为这两个类型都没有与另一个类型充分重叠。如果这是有意的,那么将表达式转换为‘ known’first.ts (2352)

我已经通过 这个,但我想要的是它的反面

编辑:

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

72816 次浏览

You cannot cast from a custom to a primitive without erasing the type first. unknown erases the type checking.

Try :

myRating as unknown as number

Or :

myRating as any

Also, remove | number from your declaration.

Update 2020

TS 3.8 update

now no need to cast using as, it is supported implicitly except in some cases. Where you can do type conversion as given in the accepted answer. Here is a good explanation of type conversion on the typescript.

type Rating = 0 | 1 | 2 | 3 | 4 | 5;
let myRating:Rating = 4
let rate:number = myRating;

TS Playground


Original Answer

I think it is fixed in the typescript update TS 3.5.1

type Rating = 0 | 1 | 2 | 3 | 4 | 5;
let myRating:Rating = 4

Now

let rate:number = myRating;

and

let rate:number = myRating as number;

both working fine.

TS Playground