I'm looking for something like this...
type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // Of course, ERROR!
const x = (a: boolean, b: B) => console.log('foo')
How can I implement this? Is it possible in Typescript?
CodePudding user response:
You can indeed. To do this, you'll need to use generics and conditional types. Like this:
type Type1 = "apple" | "grape" | "orange";
type Type2 = "apple" | "grape";
const x = <A extends boolean>(a: A, b: A extends true ? Type1 : Type2) =>
console.log("foo");
x(false, "orange"); // error
x(true, "orange"); // no error
CodePudding user response:
Please check this typescript document. https://www.typescriptlang.org/docs/handbook/2/conditional-types.html