1

I'd like to create an interface for a function using generics, such that the function takes in two arguments, and returns either the type of the first argument, or a union of the two. I had thought it was possible to do something like this:

declare interface CustomMerge {
  (x: Partial<T1>, y: Partial<T1 | T2>): T1 | T1 & T2;
}

But I get all sorts of errors about unexpected symbols here, so I suspect I'm quite a way off the mark with what I've done so far. Is this possible with typescript?

1 Answer 1

2

You must declare type variables before using them anywhere including function signatures. To do that, you have two options:

Declare on method level

declare interface CustomMerge {
   <T1, T2>(x: Partial<T1>, y: Partial<T1 | T2>): T1 | T1 & T2;
// ^^^^^^^^
}

Declare on interface level

declare interface CustomMerge<T1, T2> {
//                           ^^^^^^^^
  (x: Partial<T1>, y: Partial<T1 | T2>): T1 | T1 & T2;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is great, and has solved my problem, thanks. This is all working, I'll accept the answer once I'm able to.

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.