问题描述
给定以下代码:
type Function0<T> = () => T;
type Function1<T, A1> = (arg1: A1) => T;
type Function2<T, A1, A2> = (arg1: A1, arg2: A2) => T;
const foo: Function1<string, any> = () => "hi there";
我希望得到某种错误,因为我试图断言一些 0 参数函数是一种采用一个参数的类型.
I'd expect to get some sort of error, because I'm trying to assert some 0-argument function is a type that takes one argument.
但是,下面的编译非常好.有什么方法可以检查这些参数是否完全匹配?
However, the following compiles perfectly fine. Is there some way to type-check that these arities exactly match?
推荐答案
默认情况下,typescript 假定可以将具有较少参数的函数分配给将使用更多参数调用该函数的位置,因为额外的参数将被忽略并且它不会受到任何伤害.一个合理的假设:
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))
注意 如果传入一个参数较少的函数确实是一个错误,你应该仔细考虑,在任何情况下在运行时这样做都应该是无害的.唯一的理由可能是调用者可能会忽略传入的有用参数,但这可能无法证明强制每个人始终指定所有参数
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
这篇关于TypeScript:有没有办法对函数数量进行类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!