#Conditional callback argument's type

10 messages · Page 1 of 1 (latest)

waxen solstice
#

Hi!
I try to fix an issue where I want the type of the callback's first argument depends on another type.
Here a very simple example.
Do you have an idea?

high tuskBOT
#
oltodo#1801

Preview:ts function foo<T extends boolean>( bool: T, callback: ( value: T extends true ? string : number ) => void ) { if (bool) { callback("123") } else { callback(123) } }

waxen solstice
#

On the two lines with callback I get the error

Argument of type 'string' is not assignable to parameter of type 'T extends true ? string : number'.
#

Conditional callback argument's type

worthy crypt
#

I think you have to type cast the argument, I'm not sure if there's a cleaner way to do it

high tuskBOT
#
therealjohan#0

Preview:ts function foo<const T extends boolean>( bool: T, callback: (value: T extends true ? string : number) => void ) { if (bool) { callback("123" as T extends true ? string : number); } else { callback(123 as T extends true ? string : number); } ...

abstract night
#

you could set it up like this so the parameters form a discriminated union that you can narrow:

high tuskBOT
#
mkantor#0

Preview:```ts
type FooArgs =
| [bool: true, callback: (value: string) => void]
| [bool: false, callback: (value: number) => void]

function foo(...[bool, callback]: FooArgs)
...```

abstract night
#

you could alternatively use overload signatures, but those aren't type-checked as thoroughly as this setup is

waxen solstice
#

Thanks a lot,
using discriminated union works fine!