0

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
};
1
  • 1
    c?: never or c?: undefined are the closest you can get I think Commented Nov 1, 2020 at 16:31

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.