Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

452
Views
How can I cast custom type to primitive type?

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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!