Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters based on conditional types

Is it possible to make a function have either mandatory or optional parameters based on conditional types in TypeScript?

This is what I've got so far:

const foo = <T extends string | number>(
    first: T,
    second: T extends string ? boolean : undefined
) => undefined;

foo('foo', true); // ok, as intended
foo(2, true); // not ok, as intended
foo(2, undefined); // ok, as intended
foo(2); // compiler error! I want this to be ok
like image 619
torkel Avatar asked Sep 13 '18 16:09

torkel


People also ask

Can I use optional parameters for conditional logic?

Using Optional parameters causing conditional logic inside the methods is literally contra-productive. This argument refers to a situation when you use Optional as a method parameter just to do conditional logic based on its presence: It is an argument, but a limited one.

Is optional an argument or a method parameter?

This argument refers to a situation when you use Optional as a method parameter just to do conditional logic based on its presence: It is an argument, but a limited one. The first limitation that I see is that oftentimes you would not do any conditional logic on the argument — you just want to pass it through:

Do optional parameters exist in Java?

Unlike some languages such as Kotlin and Python, Java doesn’t provide built-in support for optional parameter values. Callers of a method must supply all of the variables defined in the method declaration. In this article, we’ll explore some strategies for dealing with optional parameters in Java.

Are all parameters required in Java?

With that being said, all parameters are required in Java! When you want to invoke a method, you have to specify all of the arguments which are used in its declaration! How to make parameters optional in Java?


1 Answers

You can do this in 3.1 using Tuples in rest parameters and spread expressions

const foo = <T extends string | number>(
  first: T, 
  ...a: (T extends string ? [boolean] : [undefined?])
) => undefined;

foo('foo', true); // ok, as intended
foo(2, true); // not ok, as intended
foo(2, undefined); // ok, as intended
foo(2); // ok

But the better way is to use overloads.

function foo2(first: string, second: boolean) : undefined
function foo2(first: number, second?: undefined): undefined
function foo2<T>(first: T, second?: boolean): undefined{
  return undefined
}

foo2('foo', true); // ok, as intended
foo2(2, true); // not ok, as intended
foo2(2, undefined); // ok, as intended
foo2(2); // ok
like image 85
Titian Cernicova-Dragomir Avatar answered Oct 18 '22 00:10

Titian Cernicova-Dragomir