#Is it possible to make a type that accepts functions with any number of parameters of a certain type
9 messages · Page 1 of 1 (latest)
@surreal grove Seems to be right:
type MyType = string;
declare const func: <T extends MyType[]>(...args: T) => void
func("foo", "bar", "baz")
Or something like:
const myFunc = <T extends MyType>(...args: T[]) => {
//...
}
I need to be able to assign to that type a function that takes a fixed number of parameters
Doesn't sound like that's safe
Well, I guess assigning the function that takes any number of params to one that expects a specific number of params should be safe, but not the reverse.
You might need to give an example of what you're doing and where you're getting an error
You can define a type that is a fixed size using something like
type ArrayOfSize<
T,
N extends number,
R extends T[] = []
> = N extends N
? number extends N
? T[]
: R['length'] extends N
? R
: ArrayOfSize<T, N, [T, ...R]>
: never;
With this you can declare a function type that takes a fixed number of elements
type MyFunc<T, N extends number> = (...args: ArrayOfSize<T, N>) => void;
let func: MyFunc<string, 5> = (a, b, c, d, e) => {};
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.