Home > Software design >  TypeScript infer second argument of a function first argument
TypeScript infer second argument of a function first argument

Time:11-08

Is it possible to infer a function argument from another argument? I want to infer 2nd argument based on inference of 1st argument.

Current code can be on GitHub enter image description here

However, what I'm looking for is a much simpler approach as shown below (but what I currently get using the code below is args being infered as any)

this._eventHandler.subscribe(onHeaderCellRenderedHandler, (_e, args) => {
  const column = args.column;
  const node = args.node;
});

So as I mentioned in the question, for that to work, I would need to infer first argument and somehow make an alias that can be used by the second argument. Is that possible with latest version of TypeScript?

CodePudding user response:

I think you want the methods to be generic not the interface, so you would put the generic at the function definition not the interface name.

export interface SlickEventHandler {
  subscribe: <T>(slickEvent: SlickEvent<T>, handler: Handler<T>) => this;
  unsubscribe: <T>(slickEvent: SlickEvent<T>, handler: Handler<T>) => this;
  unsubscribeAll: () => this;
}

then the generic will be inferred when you call the method.

  • Related