I would like to know how I can in typescript acquire all the args types of each function of the object window.
Below as you will see is the type that I have implemented but apparently I am doing it wrong ..
If someone can help me I will appreciate it.
type Arguments<F extends Function> = F extends (...args: infer A) => any ? A : never;
const x = (window: Window) => window.alert('hola')
type TestArguments = Arguments<typeof x>;
Your TestArguments
variable is an array of arguments (it even is plural). You need to either:
Access the first element:
type Arguments<F extends Function> = F extends (...args: infer A) => any ? A : never;
const x = (window: Window) => window.alert('hola')
type TestArgument = Arguments<typeof x>[0];
Or infer
only the first argument.
type FirstArgument<F extends Function> = F extends (firstArg: infer A) => any ? A : never;
const x = (window: Window) => window.alert('hola')
type TestArgument = FirstArgument<typeof x>;
Finally, to get only the functions of your function, you would do this:
type OnlyFunctions<T> = Pick<T, { [k in keyof T]: T[k] extends Function ? k : never }[keyof T]>
This basically maps through the Window
object, setting never
to variables that are not functions. Then, get the keys of that array, and use it to construct a new array (using Pick), which only has those keys.
You can combine everything using:
type OnlyFunctionsFromFirstArgument = OnlyFunctions<FirstArgument<typeof x>>;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.