2

I am curious how to create a typed function that allows you to pass the types of the function entered through as the return type and the arguments.

const preventDefault = function <T> (passThroughFunction: T) {
  return function (event, ...args): ReturnType<typeof T> {
    event.preventDefault();
    return passThroughFunction(...[event, ...args]);
  } 
}

This is broken. I am not sure how to use ReturnType properly or extract the arguments from passThroughFunction and include them in the returned function.

So I can use it like this:

<Button onSubmit={preventDefault(onSubmit)}/>

How can I do this?

1
  • Do you want information about which event called the preventDefault function ? Commented Jul 5, 2019 at 15:21

1 Answer 1

1

I think here you are better of not using the conditional types. They would require type assertions in the implementation (since conditional types are not resolved as long as they still have free type parameters)

This will work, and will actually allow contextual types to flow from the assignment target to the function you define, so if you use inline functions you will get parameter type inference

const preventDefault = function <E extends SyntheticEvent, A extends any[], R> (passThroughFunction: (e: E, ...a: A) => R) {
  return function (event: E, ...args: A): R {
    event.preventDefault();
    return passThroughFunction(event, ...args);
  } 
}

let o = () => <button onClick={preventDefault(e => e.movementX)}></button>
let o2 = () => <div onKeyDown={preventDefault(e => e.keyCode)}></div>
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.