1

I'm looking for a way to define a function that determines whether an argument is required based on a generic type. I guess this might be called "conditional 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');

1 Answer 1

3

In TypeScript, the usual way to enforce type-dependent constraints for function arguments or return type is by using overload function declarations:

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.