0

I would like to refactor the following to specify a default implementation for the extractor parameter of the handleEvent method when TEvent is of type DefaultEvent.

Instead of calling:

handleEvent<DefaultEvent>({value: "test"}, (e) => e.value);

I would like the following to be equivalent if possible:

handleEvent<DefaultEvent>({value: "test"});
type DefaultEvent = {
  value: string
}

type SpecificEvent = {
  specificValue: string
}

function handleEvent<TEvent>(
  e: TEvent,
  extractor: (e: TEvent) => string
  // default extractor implementation should be (e) => e.value when TEvent is of type DefaultEvent
  ) {
    console.log(extractor(e));
}

handleEvent<DefaultEvent>({value: "test"}, (e) => e.value);
handleEvent<SpecificEvent>({specificValue: "test2"}, (e) => e.specificValue);

1 Answer 1

1

You can handle the types via function overloading, but you still need to provide the missing extractor is the function implementation. Here's the playground

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - this works well. Is there a way to do this without explicitly having an overload for SpecificEvent? SpecificEvent could be an infinite amount of different events. Conversion of type 'TEvent' to type 'SpecificEvent' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.ts(2352) when leaving out extends DefaultEvent | SpecificEvent on the implementation.
@Dynamic I have updated the playground link in my answer, please check

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.