Tom Le
Tom Le

Reputation: 127

How can I make different generic function in type script?

I have function like this

export const registerResource = <T, H, M, I extends object, R extends object>(serverConfig: IResourceServerConfig<T, H>, option: IRegisterResourceOption<T, H, M, I, R> = {}) => {
...
}

So I will call look like this

registerResource(foo,bar)

But I would like to definition only 2 type T & H like this

registerResource<any, number>(foo,bar)

But it's not work, did I'm doing stupid and how can I resolve that.

Thanks alot

Upvotes: 0

Views: 47

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30909

If you want to specify T and H at the call site and let the remaining type arguments be inferred, that feature is not currently supported by TypeScript but hopefully it will be soon; see the open suggestion. The current workaround is to change your function into a function with some type parameters that returns a function with the remaining type parameters:

export const registerResource = <T, H>(serverConfig: IResourceServerConfig<T, H>) =>
  <M, I extends object, R extends object>(option: IRegisterResourceOption<T, H, M, I, R> = {}) => {
  // ...
};
registerResource<any, number>(foo)(bar);

(I assume your example was based on real code that is actually using M, I, and R for something, otherwise you could just replace them with {}, object, and object and not have this problem.)

Upvotes: 1

Related Questions