I'm trying to migrate my formal Javascript project to Typescript, and met very weird thing.
class A { }
function a(i: number, ...args: A[]): void {
console.log(i, args);
}
const b = new A();
const c = [new A(), new A(), new A()];
a(0, 45);
a(1, c);
a(2, b, b, b);
this is the simplication of the part of my code, there is class named 'A' and function 'a' requires a number type index and amount of instances of class 'A'.
in my expectation, this code should have to make an error. because 45 is number, and c is an array.
but it works.
it prints this to console
0 [ 45 ]
1 [ [ A {}, A {}, A {} ] ]
2 [ A {}, A {}, A {} ]
what am i missing? is it runtime bug? (I'm using deno as javascript/typescript runtime) or, is there some reason Typescript allow this?
I'm new to Typescript, so I need some advice for this.
Since A is an empty class, the only properties it will have are the properties that all objects have; things like .toString
or .valueOf
. number
s also have all of these same properties, and so do arrays, so what you're passing in does match what you've asked for.
As soon as you add properties to A, this issue will go away. For example, if you add an id: string
property, then now neither numbers nor arrays will match, since they don't have such a property.