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

71
Views
Force type change in TypeScript

I have a function that detects whether a type could be a number and changes it to Float whenever posible, this is quite usefull to me when getting data converted from csv to JSON that stringifies everything.

const possibleNum: string | number = '3'

export const changeType = (entry: string | number) => {
  return !isNaN(parseFloat(entry)) ? parseFloat(entry) : entry
}

const res = changeType(possibleNum)

console.log(typeof res)
// number

This works well with regular JavaScript, but TypeScript is not having it.

I get

`Argument of type 'string | number' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.ts(2345)`

How can I do it?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The compiler cannot understand whether you are referring string or number in parseFloat. You can add another if condition to make the compiler know your type in parseFloat is string 100%.

const posibleNum: string | number = '3'

const changeType = (entry: string | number) => {
  if(typeof entry === "number") {
    return entry
  }
  const parsedEntry = parseFloat(entry)
  return !isNaN(parsedEntry) ? parsedEntry : entry
}

const res = changeType(posibleNum)

console.log(typeof res)

Playground

about 4 years ago · Juan Pablo Isaza Report

0

Thanks to Nick Vu's answer I realised I could also do this:

parseFloat(entry as string)

const possibleNum: string | number = '3'

const changeType = (entry: string | number) => {
  const parseEntry = parseFloat(entry as string)
  return !isNaN(parseEntry) ? parseEntry : entry
}

const res = changeType(possibleNum)

console.log(typeof res)

Playground

about 4 years ago · Juan Pablo Isaza 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!