I have a function called createAction() with multiple overloads. Each overload takes an (Action) or an (Action, TObject) as parameters, and returns [Action] or [Action, TObject] respectively:
enum Action {
DataAction,
DatalessAction,
// ...
}
interface CreateAction {
(action: Action.DataAction, data: { str: string }): [typeof action, typeof data];
(action: Action.DatalessAction): [typeof action];
// ...
}
// this fails with Property '0' is missing in type (object | Action)[]
export const createAction: CreateAction = function(action: Action, data?: object) {
if (data) {
return [action, data];
}
return [action];
}
// these both succeed
var x = createAction(Action.DataAction, { str: 'foo' }),
y = createAction(Action.DatalessAction);
Alternatively, this fails with Property '1' is missing in type '[Action]' but required in type [Action.DataAction, { str: string }]:
export const createAction: CreateAction = function(action: Action, data?: object):
[typeof action] | [typeof action, Exclude<typeof data, undefined>]
{
if (data !== undefined) {
return [action, data];
}
return [action];
}
and this fails with Type 'Action' is not assignable to type 'Action.DataAction':
export const createAction: CreateAction = function(action: Action, data?: object):
[typeof action, Exclude<typeof data, undefined>?]
{
if (data !== undefined) {
return [action, data];
}
return [action];
}
Is it possible to do what I want? Here's the code in TypeScript playground.