How can I cast custom type to primitive type?

Issue

I have a 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

How can I cast my myRating into number primitive type?

It is giving me error as:

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

Edit:

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 version: 3.2.1

Solution

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.

Answered By – Steven Spungin

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.