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

149
Vistas
Typescript assign a variable of multi type containing OR ( | ) to single type variable

I have a variable that has type of number or string. How can I assign its value to a variable that accepts number only?

const id:Record<string, string|number> = {name:3}
let num: Record<string, number>;

num = id; //Shows error here

I know there can be javascript work arounds like writing a conversion function, but I am learning Typescript and want to know if there are keywords or typescript specific solutions that are meant to be used in such cases, like as Record<string,number>... that can cast it, instead of type assertion

Here is a link to the code on Typescript playground

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

It looks like you already answered your question, you can cast with the as keyword.

num = id as number

If you wanted to get fancy you could check the id's type with typeof so something like this

if (typeof id === 'number') {
  number = id
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use TypeScript 3.7's Assertion Functions, to enforce the checks in the code that didn't eliminated the wrong type:

const id:Record<string, string|number> = {name:"3"}
let num: Record<string,string>;

//the code logic safely leads to this line only if "id" contains a number value

declare function isNumId(id: Record<string, string | number>): asserts id is Record<string, string>;

isNumId(id);
num = id; // No longer shows error here

Of course, it might be simpler to just tell TS that we are sure of the type:

num = id as Record<string, string>; // No longer shows error here
about 4 years ago · Juan Pablo Isaza Denunciar

0

The Typescript playground link is bit different than what's in the question:

    const id:Record<string, string|number> = {name:"3"}
    let num: Record<string,string>;

    //the code logic safely leads to this line only if "id" contains a number value

    num = id; //shows error here

But anyway, there are two quick ways to deal with it:

    //One solution:
    
    const id2:Record<string, string> | Record<string,number> = {name:"3"}
    let num2: Record<string,string>;    
    num2 = id2;


    //Antoher solution:

    const id3:Record<string, string|number> = {name:"3"}
    let num3: Record<string,string>;
    num3 = id as Record<string,string>; 

https://www.typescriptlang.org/play?#code/LAKAkAxg9gdgzgFwAQEsAmAuASgU2gJzQB5F8UYBzAGiVPIoB8YBXAWwCMd8A+JAXiQBvGAENWODACIAzJIC+oMABscyFqwxJcBYnUpU9FbgG5QigPTmEACxxJoaO0qgUUEWiIBmOJQE8kKiJocEgIUKHWKCFK5HawfqieSJLokvawCCLkISJI6pz4SABuIkrMOGbg6vyoaMZIlnDWUADuIVz4UIW2+BUglWCWAPIwdnBQZQgosBiKitDwyOgATNh4XboIZPq0W-S8DFrrhCR7+vlcvALCYhIy8ooqamyrRzqn29SGJmCK6ss1FamfogwbmACCMDCPVoE2YUxmAwWiFq0jW70MNEMTDYBSuQlE4iksgU4CeeTYaLeGw+9AMZyMwLA6mkgLQSBEIW0NMx33qlSAA

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