Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interface Inferred from Property Not Rejecting Invalid Properties #50732

Closed
MichaelPastuch opened this issue Sep 12, 2022 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@MichaelPastuch
Copy link

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.

@MartinJohns
Copy link
Contributor

MartinJohns commented Sep 12, 2022

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
Copy link

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.

@jakebailey jakebailey added the Duplicate An existing issue was already created label Sep 12, 2022
@MichaelPastuch
Copy link
Author

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

@MichaelPastuch MichaelPastuch closed this as not planned Won't fix, can't repro, duplicate, stale Sep 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants