I'm trying to overload a function so when using the function somewhere else, it will show the result properly that is either an array of items, void, or a single item:
getSelected(type): void;
getSelected(type): IDataItem;
getSelected(type): IDataItem[];
getSelected(type:string, one:boolean = true):any {
if (!type) {
return;
}
if (one) {
return _.reduce<IDataItem, IDataItem>(sections[type], (current: IDataItem, p: IDataItem) => {
return p.selected === true ? p : current;
}, void 0);
}
return _.filter<IDataItem>(sections[type], (p: IDataItem):boolean => {
return p.selected === true && p.enabled === true;
});
}
It's giving me the error "error TS2175: Overloads cannot differ only by return type.". How can I just signal the many possibilities for the return types then?
It is worth noting a couple of points about your original code...
These are "overload signatures" - you can call these.
getSelected(type): void;
getSelected(type): IDataItem;
getSelected(type): IDataItem[];
The next line is the "implementation signature" - you cannot call it directly.
getSelected(type:string, one:boolean = true):any {
This means that as it stands, you cannot ever pass the one
argument.
type
parameter.Your overloads don't specify a type for the type
parameter, these will have the any
type - but I think you probably want to restrict this to strings. Each signature needs the annotation...
type: string
Your signature that states that if you pass true
in the one
argument, you'll get a single result. If you were to pass false, you'd get multiple results. We can now work with that, because TypeScript has been made even more awesome. See below...
Given all this information, you can use:
getSelected(type: string): void;
getSelected(type: string, one: true): IDataItem;
getSelected(type: string, one: false): IDataItem[];
getSelected(type: string, one: boolean = true): any {
// ... code!
}
When you call this, the types will be inferred based on the arguments passed. This is the shape of it, with your code removed from the actual method...
interface IDataItem {
name: string;
}
class Example {
getSelected(type: string): void;
getSelected(type: string, one: true): IDataItem;
getSelected(type: string, one: false): IDataItem[];
getSelected(type: string, one: boolean = true): void | IDataItem | IDataItem[] {
// ... code!
}
}
const example = new Example();
// void return
example.getSelected('just type');
// IDataItem
const a = example.getSelected('x', true);
// IDataItem[]
const b = example.getSelected('x', false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With