#Conditional callback argument's type
10 messages · Page 1 of 1 (latest)
Preview:ts function foo<T extends boolean>( bool: T, callback: ( value: T extends true ? string : number ) => void ) { if (bool) { callback("123") } else { callback(123) } }
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
I think you have to type cast the argument, I'm not sure if there's a cleaner way to do it
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); } ...
you could set it up like this so the parameters form a discriminated union that you can narrow:
Preview:```ts
type FooArgs =
| [bool: true, callback: (value: string) => void]
| [bool: false, callback: (value: number) => void]
function foo(...[bool, callback]: FooArgs)
...```
you could alternatively use overload signatures, but those aren't type-checked as thoroughly as this setup is
Thanks a lot,
using discriminated union works fine!