There is a function that requires specific arguments, including a callback function that takes an object or an array of objects based on an isArray parameter.
I am attempting to create a new feature.
type Option = {
name: string
value: string
}
type FunctionProps<IsArray extends boolean | undefined> = {
isArray?: IsArray
callback: IsArray extends false
? (options: Option) => void
: (options: Option[]) => void
}
const func = <T extends boolean | undefined = false>({isArray, callback}: FunctionProps<T>) => {
const options: Option[] = /* */
const currentOption: Option = /* */
if (isArray) {
callback(options) // Argument of type 'Option[]' is not assignable to parameter of type 'Option & Option[]'.
else {
callback(currentOption) // Argument of type 'Option' is not assignable to parameter of type 'Option & Option[]'.
}
}
While everything works correctly when calling func, TypeScript insists on having the types Option & Option[]
as arguments when calling the callback function inside func. I can specify the type explicitly by calling
callback(value as Option & Option[])
, but this can be confusing and make it unclear what is happening inside ultimately. Is there a way to define the type more clearly? P.S. Declaring the function type as shown below does not change anything.
type FunctionProps = {
isArray: false
callback: (options: Option) => void
} | {
isArray: true
callback: (options: Option[]) => void
}