Comment by sally_glance
4 days ago
I think the problem is the union argument type - intuitively we read "array of strings OR numbers", but actually it means "array of strings AND numbers". Probably generics would be more appropriate here, with the type param constrained to string or number. Then tsc would also complain about pushing a number without checking the item type before.
If it's an "array of strings AND numbers", then it should not be allowed to call the function with a string[], because those are different types.
That would be the sound way to do things, but it's also surprisingly common for arrays for some reason. It also doesn't get checked compile time in Java, although it does throw an exception because the arrays are type-enforced at runtime at least.
This compiles fine:
That’s barely scratching the surface.
In TypeScript the following is also valid:
class Something{
}
class SomethingElse{
}
function AddSomething(v: Something)
{
}
var ex = new SomethingElse{
};
AddSomething(ex);
Why does it work? Because in TypeScript as long as you have a “shape” that fits, it’s the “same type.”
Complete and utter insanity to me, to pretend there’s any real type checking, when types are entirely fake and made up.
That's because it's structurally typed (as opposed to nominally typed). I don't happen to prefer it, but I don't think it's fair to conflate that with unsoundness like the example given above; it's totally possible to have a sound structural type system. TypeScript doesn't happen to be sound, but it's not because of that.
2 replies →