Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 posibleNum: string | number = '3'

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

const res = changeType(posibleNum)

console.log(typeof res)
// number

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

I get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading