How can I define keys: a, b, c, bar
as undefined/null/optional type if foo is false? In other words, I need these properties to be mandatory only if foo is true.
interface ObjectType {
foo: boolean;
a: number;
y: string;
c: boolean;
bar?: { x: number; y: string; z: boolean };
}
Thanks! :)
How can I define keys: a, b, c, bar
as undefined/null/optional type if foo is false? In other words, I need these properties to be mandatory only if foo is true.
interface ObjectType {
foo: boolean;
a: number;
y: string;
c: boolean;
bar?: { x: number; y: string; z: boolean };
}
Thanks! :)
Share Improve this question asked Nov 20, 2020 at 17:13 Vinay SharmaVinay Sharma 3,8176 gold badges38 silver badges69 bronze badges1 Answer
Reset to default 10I think the most straight forward way is to simply use union types.
interface RequiredObjectType {
foo: true;
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface OptionalObjectType {
foo: false;
a?: number;
y?: string;
c?: boolean;
bar?: { x: number; y: string; z: boolean };
}
type AnyObjectType = RequiredObjectType| OptionalObjectType;
You could of course abstract the repeated properties out if needed to save typing on types that will change overtime.
interface ObjectTypeValues {
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface RequiredObjectType extends ObjectTypeValues {
foo: true
}
interface OptionalObjectType extends Partial<ObjectTypeValues> {
foo: false
}
type AnyObjectType = RequiredObjectType | OptionalObjectType;
You'll get type inference for free as well.
if (type.foo) {
// im the required type!
// type.a would be boolean.
} else {
// im the optional type.
// type.a would be boolean?
}