Issue
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?
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)
Answered By - Nick Vu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.