我正在寻找一种定义函数的方法,该函数确定是否需要基于泛型类型的参数。我猜这可能被称为“条件限制”。
// 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');
答案 0 :(得分:3)
在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();