Not planned
Description
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
.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
MartinJohns commentedon 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 commentedon Sep 12, 2022
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 commentedon Sep 13, 2022
Thank you for the swift responses. I am happy with the explanation and can work around my issue.