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! :)
I 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?
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With