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

155
Vistas
Why does assigning a variable of type any change the type of the variable it is assigned to?

Let's look at the following example:

let a: string = "hello world"
let b: number = 23
let c: any = 23

console.log(typeof a) // "string"
console.log(typeof b) // "number"
console.log(typeof c) // "number"

a = b // Fails!
a = c // Works!
console.log(typeof a) // "number"

a = b // Fails!
a = "Hallo Welt" // Works!
console.log(typeof a) // "string"
  1. Why is it possible to change the type of a non-any variable? I would expect x: any = y: string | number | ..., but not x: string | number | ... = y: any, except if the any variable is inferenced to a matching type.

  2. Why can I assign a string after "changing" the type to number, but no number?

  3. How do I prevent a variable from ever changing its type.

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

0

According to TypeScript Documentation:

Don’t use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable. This can be very helpful when you are first migrating a JavaScript project to TypeScript as you can set the type for stuff you haven’t migrated yet as any, but in a full TypeScript project you are disabling type checking for any parts of your program that use it.

In cases where you don’t know what type you want to accept, or when you want to accept anything because you will be blindly passing it through without interacting with it, you can use unknown.

let a: string = "hello world"
let b: number = 23
let c: unknown = 23

console.log(typeof a) // "string"
console.log(typeof b) // "number"
console.log(typeof c) // "number"

a = b // Fails!
a = c // Fails!
a = "Hallo Welt" //Works!
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