Typescript - make an optional property required when another property is present

Viewed 3779

I have proptypes shown below

interface Props {
resource: string;
create?: boolean;
route?: string;
}

As can be seen above, create and route are optional props. However, I would like to implement the types such that if create prop is present then route must now be required. Anyone have any ideas how to do this?

3 Answers

You should group these props and make that grouped prop optional as

interface RouteProps{
create: boolean;
route: string;
}

interface Props {
resource: string;
routeInfo?: RouteProps;
}

You can split it into a union of two types and use create with a literal type:

type Props = {
  resource: string;
  create?: false;
  route?: string
} | {
  resource: string;
  create: true;
  route: string;
}

although I like @DevLoverUmar 's solution more. You actually have the option to do something like this with typescript:

this might be what you re looking for. But you would have to explicitly set TArgs<true>

type TArgs<T extends boolean> = {
   a: T,
   b: string,
   c: T extends true ? string : null
 }

Example of how it could look with a factory function:

type TArgs<T extends true | false> = {
    a: T,
    c?: T extends true ? string : null
}

const argsFactory = <T extends boolean>(a: T, c: T extends true ? string : null): TArgs<T> => {
    return {
        a,
        c
    }
}

// Works
argsFactory(true, "string");
argsFactory(false, null);

// Doesnt Work
argsFactory(false, "some String");
argsFactory(true, null)
Related