Skip to content

Cast permitted with missing properties on object literals #13788

@mathias999us

Description

@mathias999us

TypeScript Version: 2.1.1 / nightly (2.2.0-dev.201xxxxx)

Code

interface ITestOne {
    a: string;
    b?: string;
}

var test1: ITestOne = {} as ITestOne; // ALLOWED - Why is this allowed?
var test2: ITestOne = { b: 'blah' } as ITestOne; // ALLOWED - Why is this allowed?
var test3: ITestOne = { b: 'blah', x: 'meh' } as ITestOne; // ERROR - Property a is missing

Expected behavior:

Expected behavior is that test2 case is not permitted. NOTE: This was working correctly as of TypeScript 1.7.

Test3 is an example of how to perturb the "correct" behavior.

I have not been able to find any documentation about why test1 is allowed. One could make the case for filling out an empty object literal after it has been instantiated empty, but this seems like a dangerous thing to allow. Again it permits the case where we have an object of ITestOne that does not meet the interface definition.

Actual behavior:
test2 passed compiler checks, but produces an invalid object literal without property a.

See SO post for some further background:
http://stackoverflow.com/questions/41941125/intellisense-with-union-types

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions