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"
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.
Why can I assign a string after "changing" the type to number, but no number?
How do I prevent a variable from ever changing its type.
According to TypeScript Documentation:
Don’t use
anyas a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treatsanyas “please turn off type checking for this thing”. It is similar to putting an@ts-ignorecomment 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!