Is it possible to have different type be inferred based on the params passed?

Viewed 39

Based on this example:

type FooProps = {
 baseProp: string
} & ({
 cb: (value: number) => void;
 selectRange: false
} |
{
 cb: (value: [number]) => void;
 selectRange: true
}
)

Then what I am looking to do is, change the type value param in cb, based on the value of selectRange.

I'd like to use it in a React component like so:


const FooComp : React.FC<FooProps> = ({cb, selectRange}) => {
...
if (selectRange) {
 cb([1,2])
} else {
 cb(1)
}
...
}

Here's a codesandbox to demonstrate the issue. And a ts playground where it works

0 Answers
Related