I have constructed the following code, which compiles without any warnings or errors:

const x: number[] = [1,2,3];
const y: any[] = x;

y[0] = "hello";
y[1] = x;

const x0: number = x[0];
const x1: number = x[1];

console.log(typeof x0);
console.log(typeof x1);
console.log(x as any === x1 as any);

But even though I've declared x0 and x1 to be numbers without error and without an explicit cast, typeof reveals that they're not numbers at all, and by casting x and x1 to any, we can see that they're the same object, even though they have different and incompatible declared types! (Indeed, x === x produces "error TS2367: This comparison appears to be unintentional because the types 'number' and 'number[]' have no overlap.")

It seems to me that upcasting to any[] isn't safe and shouldn't be allowed. This could be solved by introducing immutable types, since upcasting to immutable any[] would be safe since it's always safe to read an array as if one doesn't know the type of its contents. Has such a fix ever been proposed?

I AM NOT ASKING WHY ARRAYS ARE COVARIANT. I AM ASKING IF OR WHY IMMUTABLE TYPES WERE NOT CONSIDERED IN ORDER TO PREVENT BAD VALUES GETTING ASSIGNED TO AN ARRAY.

0

There are 0 best solutions below