Why does assigning a variable of type any change the type of the variable it is assigned to?
Solution 1:
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 treatsany
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 asany
, 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!