Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda