Shouldn't this fail?
class Animal { }
class Person { }
type MyUnion = Number | Person;
var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Shouldn't this fail?
var x: MyUnion = "jjj"; // Shouldn't this fail?
Is there a way to enforce type checking in this case?
TypeScript handles type compatibility based on structural subtyping
.
Structural typing is a way of relating types based solely on their members
In particular for classes:
When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.
More info at https://www.typescriptlang.org/docs/handbook/type-compatibility.html#classes
It'll fail if Animal
or Person
define anything:
class Animal { name: string; }
class Person { age: Number; }
type MyUnion = Number | Person;
var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Fails now
var x: MyUnion = "jjj"; // Fails now
Since you haven't defined anything in Animal
or Person
, a string (or anything, actually), fulfills the contract you're asking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With