Closed
Description
TypeScript Version: 2.1 and current PlayGround
Code
// A *self-contained* demonstration of the problem follows...
interface IDogArgs {
paws?: number;
}
class Dog {
constructor(args: IDogArgs) {
}
}
interface ICatArgs {
claws: string;
}
class Cat {
constructor(args: ICatArgs) {
}
}
interface IHowToMakeDog {
ctor: new (args: IDogArgs) => Dog;
args: IDogArgs;
}
interface IHowToMakeCat {
ctor: new (args: ICatArgs) => Cat;
args: ICatArgs;
}
type AnimalMakers = IHowToMakeDog | IHowToMakeCat;
// OK
var testDog: AnimalMakers = {
ctor: Dog,
args: {
paws: 4
}
};
var testCat: AnimalMakers = {
ctor: Cat,
args: {
claws: 24, // Why is this okay?
bogus: false // What is this okay?
}
};
Expected behavior:
Should be restricted from assigning a number to the claws property.
Should be restricted from assigning "bogus" property.
Actual behavior:
The above code is valid and passed typescript compiler checks, and I am able to make an assignment that does not meet the requirements of any of the types specified in the AnimalMakers union type. The key seems to be that the paws property on IDogArgs is optional. If this property is required, the compiler provides errors on the testCat assignment as expected. Also, the compiler correctly provided errors in this scenario as of TypeScript 1.8.