TypeScript: Is there a way to typecheck function arity?

By default typescript assumes that a function with fewer parameters can be assign to where a the function will be called with more parameters, as the extra arguments will get ignored and no harm will come of it. A reasonable assumption:

const foo: Function1<string, any> = () => "hi there";
foo("Ignored, but why would that be a problem ?")

That being said, we can in some circumstances force the passed in function to have the same number of parameters as the expected number of parameters. This scenario involves passing the function to another function and using some conditional types to force an error if there are too few arguments:

type IsArg1Valid<T extends (...a: any) => any, E> = Parameters<T>['length'] extends 1 ? {} : E ;
function withFoo<T extends (arg: string) => any>(foo:  T & IsArg1Valid<T, "You need to pass in a function with a first argument">){

}
withFoo(()=> {}) //Type '() => void' is not assignable to type '"You need to pass in a function with a first argument"'.
withFoo(a=> console.log(a)) //ok
withFoo((a, b)=> console.log(a)) 

Play

Note You should think long and hard if passing in a function with fewer parameters is truly an error, it should be harmless to do so in all circumstances at runtime. The only argument for it might be that the caller might overlook useful passed in parameters, but this might not justify forcing everyone to specify all paramters all the time

Loading...

(Visited 2 times, 1 visits today)