I'm trying to make a function overloading for the search() function. This method must have different search actions.
- search with only string type.
search(key: string): IPagination<Employee[]>;
- search with
BasicFiltertype:search(x: BasicFilter): IPagination<Employee[]>;
- search with
PaginatedFiltertype:search(y: PaginatedFilter): IPagination<Employee[]>;
How can i check the type of this interfaces in search(args: any): any; method?
Tried doing the following:
if (typeof args === BasicFilter) {
console.log('searched with basic filter arguments');
}
TS message: 'BasicFilter' only refers to a type, but is being used as a value here.
Error message: BasicFilter is not defined
Here are the following codes:
The Interfaces
interface PageData {
pageIndex: number;
pageSize: number;
}
interface Employee {
id: number;
name: string;
}
interface BasicFilter {
key: string;
is_archived: boolean;
}
interface PaginatedFilter {
key: string;
is_archived: boolean;
page: PageData;
}
interface IPagination<T> {
length: number;
list: T;
}
The Class
class Service {
constructor(public name) {}
search(x: BasicFilter): IPagination<Employee[]>;
search(y: PaginatedFilter): IPagination<Employee[]>;
search(key: string): IPagination<Employee[]>;
search(args: any): any {
if (typeof args === 'string') {
console.log('searched with keyword only');
}
if (typeof args === 'object') {
console.log('searched with object arguments');
}
}
}
Usage
const service = new Service('Serbisyo publiko');
service.search({ key: 'some key', is_archived: false });
const default_page: PageData = { pageIndex: 0, pageSize: 15 };
service.search({ key: 'some queries', is_archived: true, page: default_page });
service.search('filtering data..');
The Output
searched with object arguments
searched with object arguments
searched with keyword only