#Typing an object that contains multiple functions with different sets of parameters

22 messages · Page 1 of 1 (latest)

rain charm
#

Good afternoon,
This seems simple enough, but I am unsure how to proceed. I'd like to create an object that has a function for every key in an enum. But each function has a different set of parameters.
How can I type this object so that accessing the function from the object has the correct parameters as the original function?

Using ...params: any[] isn't giving me the outcome I was expecting.

export const functions: {
  [key in Functions]: (...params: any[]) => void;
} = {
  [Functions.One]: (userId: number) => {},
  [Functions.Two]: (
    userId: number,
    x: number,
    y: number
  ) => {},
};

Thanks!

gusty flume
#

if you declare the type of the variable using var whatever: YourTypeHere typescript does not infer the type assigned to the variable

#

instead you want to use satisfies to tell typescript to check the constraint but still infer the type of the variable from its assignment

twilit lichenBOT
#
webstrand#0

Preview:ts ... export const functions = { [Functions.One]: (userId: number) => {}, [Functions.Two]: ( userId: number, x: number, y: number ) => {}, } satisfies { [key in Functions]: (...params: never) => void; }

gusty flume
#

note that in other cases you may need to use {} as const satisfies YourTypeHere this is because typescript does not always precisely infer the type of mutable objects for reasons of convenience. But you don't need as const here

rain charm
#

Ooh, satisfies. I keep seeing this keyword and forgetting to use it

gusty flume
#

yeah it's pretty awesome

#

I use it in loads of places it's a nice assert

rain charm
#

Is there a benefit to never over any[] in the satisfies?

gusty flume
#

I used ...params: never instead of ...params: any[] because the former is the "top type"

rain charm
#

Both seem to do the job, but I see you've done never

#

Ah the answer was on the way!

gusty flume
#

in this case it doesn't strictly matter

#

but if you mean "this function is callable but I have no idea what the arguments are" then (...params: any[]) => void used in the wrong context can be "this function is callable with any number of arguments including no arguments"

#

I try to avoid any if at all possible, though sometimes it's not possible to avoid it

rain charm
#

Yeah I endeavour to avoid any too

#

So if I made a function without params in this object, never would be more correct

gusty flume
#

well kinda, strictly a callable function with no arguments is (...params: []) => void though I would never type it that way

rain charm
#

Thanks for your help!

#

!resolved

south creek
#

!:vari%