computer
profile

Felix Domingos

@felix-domingos

1

FOLLOWERS

5

FOLLOWING

Answer

How could I have optional/flexible TypeScript typed in a function signature?

I have the following example function signature:

(e: Event | React.SyntheticEvent<Element, Event>, value: number | number[]) => void

But what I really want is to have the ability to accept functions that have any combination of:

(e: Event, value: number) => void
(e: Event, value: number[]) => void
(e: React.SyntheticEvent<Element, Event>, value: number) => void
(e: React.SyntheticEvent<Element, Event>, value: number[]) => void

But TypeScript is really annoying and would only accept the exact same signature... What is the correct way to make the TypeScript function signature a little bit more "acceptable", "flexible" or "smarter"?

I kinda don't want to have the following though:

type MyFuncSig = 
  (e: Event, value: number) => void |
  (e: Event, value: number[]) => void | 
  (e: React.SyntheticEvent<Element, Event>, value: number) => void |
  (e: React.SyntheticEvent<Element, Event>, value: number[]) => void;

Edit: The original function signature in question, is actually from Material UI's Slider (see: onChange and onChangeCommitted)

test-img

@