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
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.
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:
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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With