TypeScript - 基于泛型类型的条件函数 arity



我正在寻找一种方法来定义一个函数,该函数根据泛型类型确定是否需要参数。我想这可以称为"条件性"。

// I want the function to expect no arguments if the generic type is never
foo<never>();
// This would complain that zero arguments are expected
foo<never>(4);
// These would work based on a non-never type
foo<number>(4);
foo<string>('bar');

在 TypeScript 中,对函数参数或返回类型强制实施类型相关约束的常用方法是使用重载函数声明:

function foo<T extends never>();
function foo<T>(a: T);
function foo<T>(a?: T) {
// ... implementation
}
// This is ok
foo<never>();
// This is not ok
foo<never>(4); // Argument of type '4' is not assignable to parameter of type 'never'.
// as well as this
foo<number>(); // Type 'number' does not satisfy the constraint 'never'
// These are ok
foo<number>(4);
foo<string>('bar');
// however, nothing prevents the compiler from inferring the type for you
foo(4);
foo();

最新更新