How can I cast custom type to primitive type?

Solution 1:

Try:

myRating as unknown as number

Also, remove | number from your declaration.

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

Solution 2:

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