Reputation: 4760
I have a generic interface
export interface Method<T> {
(answer: T): T;
}
I want to create an interface where I have fn function
interface Wrapper {
fn: <T,>(a: T ) => T
}
but instead of manually writing the function type I want to use the interface
interface MethodWrapper {
fn: Method
}
I want the fn
to be generic at fn level not at the interface level. Is it possible?
ts-playground link
Upvotes: 2
Views: 696
Reputation: 330456
TypeScript's type system lacks the expressiveness to programmatically transform Method<T>
into Wrapper
. You'd need to move the scope of the generic type parameter T
around in ways that can't be done.
If TypeScript had generic values as requested in microsoft/TypeScript#17574, then you might be able to say something like:
// Invalid TypeScript, don't do this
interface Wrapper {
fn: forall T. Method<T>;
}
or
// Invalid TypeScript, don't do this
interface Wrapper {
fn: <T> Method<T>;
}
But it doesn't so we can't.
You can almost do it the other way around and define Method<T>
in terms of Wrapper
, using instantiation expressions. I say "almost" because it requires that you drop down to the type level and acquire (or pretend to acquire) a value wrapper
of type Wrapper
before lifting back up to the type level. Like this:
declare const wrapper: Wrapper; // pretend to have this
type Method<T> = typeof wrapper.fn<T> // instantiate fn with <T>
// type Method<T> = (a: T) => T
Depending on your use case that may or may not be helpful.
Upvotes: 2
Reputation: 559
Not sure I understand your question fully, but guessing from your TS playground you need to pass the type of the generic:
interface MethodWrapper {
fn: Method<T> // T should be the type you want fn to receive
}
Upvotes: 0