#How to conditionally make a parameter optional

25 messages · Page 1 of 1 (latest)

prime creek
#

I would like to have the 4th parameter only when Timing is "after" otherwise id like to have it to be left away

vapid tundra
#

... : void

#

Or use overloads

prime creek
#

@vapid tundra when doing it void it still wants a 4th parameter by not making it optional

#

what are overloads?

vapid tundra
#

!hb overloads

random escarpBOT
vapid tundra
#

... bad link

#

Huh, I thought I'd seen someone using void with a conditional type to do that...

prime creek
#

sadly not

#

its complaining that it needs mor params

random escarpBOT
#
Gerrit0#7591

Preview:```ts
function foo<T extends "now" | "after">(
timing: T,
...[duration]: T extends "after" ? [string] : [void]
) {}

foo("now")
foo("after", "")```

vapid tundra
#

Very ugly, but...

prime creek
#

@vapid tundra Oh it has to be a rest parameter

#

Ahhh

#

genius

#

when you use extends in a type it for some reason loses context of which propeties actually exist on the object

#

even if both types just have one propety difference

#

wreidly

#

uhhm

vapid tundra
#

Could probably use [] instead of [void], more semantically correct anyways

prime creek
#

@vapid tundra that was it, thank you!

#

!solved