El Anonimo
El Anonimo

Reputation: 1870

Typescript: require param when another is required

I have an interface where the c param should only be required when the a one is true.

interface IArgs {
  a: boolean,
  b: string,
  c: string
}

The below seems to work but how do I omit the c param in the first clause? Used type since an interface would return an error.

type TArgs = {
  a: true,
  b: string,
  c?: string
} | {
  a: false,
  b: string,
  c: string
};

Upvotes: 0

Views: 158

Answers (1)

Michel Vorwieger
Michel Vorwieger

Reputation: 722

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)

Upvotes: 1

Related Questions