There seems to be a misconception about the any
type.
Let's start by understanding what the any
type is. According to the documentation:
Sometimes, we encounter situations where we need to work with variables whose types are unknown during development. These values could be obtained from external sources like user input or third-party libraries. In such cases, we can choose to bypass type checking and allow the values to go through the compilation process without strict type constraints.
Using the any
type essentially instructs the compiler to forgo type checking and simply let the values pass through unchecked.
If we want the compiler to perform type checking during compilation, we should explicitly specify the types we expect. In your example, the types of f1
and f2
are predetermined at compile time.
var f1 = new Array<string>(0);
f1 = ['a', 'b', 'c']; // OK
f1 = [1, 2, 'a']; // Type error
var f2 = new Array<number>(0);
f2 = [1, 2, 3]; // OK
f2 = [1, 2, 'a']; // Type error
Alternatively, we can simplify the code even further:
var f3 = [1, 2, 3]; // Now f3 is of type number[]
f3 = [1, 2, 'a']; // Type error
In conclusion: by eliminating the use of any[]
in your code, you can achieve the desired outcome.