Skip to content

Interface Inferred from Property Not Rejecting Invalid Properties #50732

Not planned
@MichaelPastuch

Description

@MichaelPastuch

Bug Report

πŸ”Ž Search Terms

"type infer", "conditional interface"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (4.2, 4.6, 4.8, and nightly)

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type TNumTypes = 1 | 2 | 3;

interface IBase {
	type: TNumTypes;
}

interface IString extends IBase {
	type: 2;
	string: string;
}

interface IDate extends IBase {
	type: 3;
	date: Date;
}

const test: IBase | IString | IDate = {
	type: 3,
	string: "test"
};

πŸ™ Actual behavior

The test object with a type value of 2 should flag the string property as invalid, since it is not in IBase or IDate, but the object is considered valid.

πŸ™‚ Expected behavior

The test object should infer its interface from the value of type. Any valid value could be an IBase, but a value of 2 should not be an IDate and a value of 3 should not be an IString.

Activity

MartinJohns

MartinJohns commented on Sep 12, 2022

@MartinJohns
Contributor

Duplicate of #20863. Your object is a valid IBase. Additional properties are allowed. Objects are not sealed.

You should instead create a discriminated union type.

fatcerberus

fatcerberus commented on Sep 12, 2022

@fatcerberus

IIRC this is a limitation of excess property checking; if the property exists in any of the union constituents, it isn't flagged. Note that excess property errors are not type errors per se; TypeScript doesn't support exact types.

MichaelPastuch

MichaelPastuch commented on Sep 13, 2022

@MichaelPastuch
Author

Thank you for the swift responses. I am happy with the explanation and can work around my issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

        Participants

        @fatcerberus@MartinJohns@jakebailey@MichaelPastuch

        Issue actions

          Interface Inferred from Property Not Rejecting Invalid Properties Β· Issue #50732 Β· microsoft/TypeScript