Consider the code snippet below:
let x: string = "hello world"
let y: number = 23
let z: any = 23
console.log(typeof x) // "string"
console.log(typeof y) // "number"
console.log(typeof z) // "number"
x = y // Fails!
x = z // Works!
console.log(typeof x) // "number"
x = y // Fails!
x = "Hallo Welt" // Works!
console.log(typeof x) // "string"
What allows changing the type of a non-'any' variable to 'any'? Shouldn't it be
, instead ofx: any = y: string | number | ...
, unless the 'any' variable is inferred to match a specific type?x: string | number | ... = y: any
Why can a string be assigned after converting the type to number, but not a number?
Is there a way to prevent a variable from ever changing its type?