Typescript: require param when another is required

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)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top