Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!