Skip to content

Improper Assignment Allowed on Properties of Unioned Interface type #14369

Closed
@mathias999us

Description

@mathias999us

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions