function mutateArray(
arr: (string | number)[]
) {
arr.push(1);
}
const a: string[] = ["one", "two"];
mutateArray(a);
a is now a string[] with a number inside function mutateArray(
arr: (string | number)[]
) {
arr.push(1);
}
const a: string[] = ["one", "two"];
mutateArray(a);
a is now a string[] with a number insideIs there a name for this failure mode?
I came across it on ThePrimeagen's YouTube channel: https://youtu.be/u1WmiqlrqL0
In TypeScript the following is also valid:
class Something{
value: Number
}class SomethingElse{
value: Number
foo: String
bar: SomeOtherThing[]
}function AddSomething(v: Something)
{
v.value += 1;
}var ex = new SomethingElse{
value: 3,
foo: “TypeScript is fake types”,
bar: []
};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.
This compiles fine:
class A {}
class B1 extends A {}
class B2 extends A {}
public class MyClass {
public static void main(String args[]) {
A[] array = new B1[1];
array[0] = new B2();
}
}"allowing this enables many common JavaScript patterns"
Honestly at this point they should make a new strict "no js" mode, as the ecosystem likely has reached a tipping point where you can get by without mixing typed and untyped js at compile time. Wonder if targeting wasm directly would help ensure those boundaries are ensured...