As a follow on to yesterday’s post (inspired by @dagda1's question), what is the difference between using any[], unknown[] or never[] as constraints to the function rest parameter in #TypeScript ?
The answer is that if you use a type parameter for the args, there isn’t much difference. You can’t call the function with anything that isn’t typed as A, since you can’t assign a concrete type to a type parameter.
2/6🧵 typescriptlang.org/play?#code/GYV…
If the rest parameter is in a function type constraint (the way I recommend you don’t do in the previous post), then we get differences.
3/6🧵
F extends (...a: unknown[]) => void is a function that should be able to handle any arguments, so we can call it with anything. This means if we try to pass in, for example, a function taking a string we get an error.
F extends (...a: never[]) => void is a function we can’t call, since nothing will ever be compatible with never. But since we can’t call it, it is safe to pass in any function
F extends (...a: any[]) => void is the more unsafe version (any is unsafe, what a surprise!). We can both pass in any function AND call the function with any arguments, which is probably not a good idea.
The first problem is usually how we choose our type parameters. There are two common approaches.
2/5🧵
Define a type parameter for the whole function, then use Parameters and ReturnType. While this approach might work in most cases, usually the types of interest are the parameters and return type, not the whole function type.
3/5🧵