Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

73
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda