0

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?

1
  • I think you're looking for generics Commented Feb 25, 2022 at 9:47

1 Answer 1

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.