How TypeScript's 'Evolving any' works

There’s a subtle behavior in TypeScript that surprises many developers. A variable can start with the type 'any,' but then its type can change (or 'evolve') as you assign values to it. This is called 'Evolving any.' This happens when you declare a variable without a type and without an initial value. When you do this, TypeScript doesn’t know what the variable should be. So it temporarily treats it as 'any.' But as soon as you assign a value, TypeScript refines the type based on that value, and it continues to update that type as you assign new values later. In other words, the type 'evolves' to match the values being assigned. This is different from explicitly setting the type as 'any'. When you explicitly set the type of a variable as 'any,' the variable always remains 'any.' TypeScript won't do any type checking on it, and you lose type safety completely. But when you declare a variable without a type and without an initial value, it starts as 'any,' but each assignment changes the inferred type. So, 'evolving any' still preserves type checking, while an explicit 'any' does not. Arrays evolve as well. If you start with an empty array, then TypeScript infers it as 'any[]' initially. But once you start adding values, the array type evolves accordingly. After pushing numbers, it becomes 'number[].' After later pushing a string, it becomes '(number | string)[].' TypeScript does this because it is designed to support gradual typing. Sometimes you genuinely don’t know the variable value at the moment of declaration, and 'evolving any' allows type inference to 'catch up' later. #TypeScript #JavaScript #Coding #Programming #WebDevelopment

  • text

To view or add a comment, sign in

Explore content categories