Search code examples
javascripttypescripttypesconditional-types

Make a property mandatory based on another property of the same object in typescript


I have an use case

  interface MakeMandatory {
    name: string;
    age?: number; //
    isHiringPossible?: boolean
  }

Here, age and isHiringPossible is optional but if age contains value then isHiringPossible should also contain value and vice versa. Any thoughts?


Solution

  • You actually have two types. One where age and isHiringPossible are both missing, and one where both are required. And what you want is a type that is the union of those two types.

    interface MakeMandatoryMinimal {
        name: string;
        age?: undefined;
        isHiringPossible?: undefined
    }
    
    interface MakeMandatoryComplete {
        name: string;
        age: number;
        isHiringPossible: boolean
    }
    
    type MakeMandatory = MakeMandatoryMinimal | MakeMandatoryComplete
    

    Now you can test age which will prove that isHiringPossible exists, like so:

    declare const data: MakeMandatory // pretend we have object of type MakeMandatory
    
    data.isHiringPossible // type: boolean | undefined
    
    if (data.age) {
        data.isHiringPossible // type: boolean
    }
    

    See Playground