I’m trying to apply a type if the object has x
. What I tried had unexpected results. Can anyone explain the results and/or offer a solution?
interface BaseType {
x?: number;
a?: string;
b?: number;
}
interface WithoutX extends Omit<BaseType, "x"> {
};
interface WithX extends Omit<BaseType, "x"> {
x: any;
y: string;
};
type ConditionalType = WithX | WithoutX;
// No `x` or `y`, conforms to WithoutX
const validObject1: ConditionalType = {
a: "hello",
b: 42
};
// Has `x` and `y`, conforms to WithX
const validObject2: ConditionalType = {
a: "world",
x: 10,
y: "required"
};
// This should cause a type error because `y` is required if `x` is present
const shouldBeInvalidButIsNot: ConditionalType = {
a: "typescript",
x: 10
};
const invalidObjectBecauseX: WithoutX = {
a: "typescript",
x: 10
};
const invalidObjectBecauseYMissing: WithX = {
a: "typescript",
x: 10
};
Playground