Consider the following snippet (see also TS Playground ):
var nr: number = 123456; var str: string = "2015-01-01T12:00:00"; var both: number | string = 123456; var myDate: Date; myDate = new Date(nr); myDate = new Date(str); myDate = new Date(both);
This final line gives a compiler error:
Argument of type number | string
number | string
not assigned to a parameter of type 'string'. The type 'number' is not assigned to the type 'string'.
However, since there is a Date(...)
constructor for both types, I would assume that the above would work.
I can get around the problem because there is another constructor with the any
parameter:
myDate = new Date(<any> both);
But what if this constructor was not, for example. if this scenario occurred in my own class?
Is there a way to make this work correctly? Or is it a type of association that describes the smell of design, indicating that my definitions need to be changed?
I checked the TS Handbook , but there is no section on connection types in it. I tried to solve it myself, but I did not pass the <any>
trick mentioned above. I looked at suggested duplicates and similar questions on SO, but have not yet found an answer.
source share