I working in react typescript. I have created a common utility function like this -
interface IUpdatedRows {
rowsPerPage: number;
// this is where the confusion is -
rows: {
id: number;
name: string;
description: string;
role: string;
manager: string;
total_tasks: number;
annotator: number;
qc: number; }[];
//
page: number;
}
export const updatedRows = (args: IUpdatedRows) => (args.rowsPerPage > 0
? args.rows.slice(args.page * args.rowsPerPage, args.page * args.rowsPerPage args.rowsPerPage)
: args.rows
);
Here I will use updatedRows function from separate components having different set of rows. Above situation works well only for 1 component where row have exactly the type I have mentioned above i.e.
row: {
id: number;
name: string;
description: string;
role: string;
manager: string;
total_tasks: number;
annotator: number;
qc: number; }[];
In a different component row have these fields -
row: {
id: number;
name: string;
code: string;
type: string;
added_by: string;
added_on: string;
};
I am not sure how to give a common type in a utility file for row
which will be applicable for all the components. Any help, pointers is highly appreciated.
CodePudding user response:
Asuming IUpdatedRows
interface itself and the related function updatedRows
does not need to know anything about the type of Rows (except the fact that is should be an array) and they should be used for different types of Rows - you can use Generics.
interface IUpdatedRows<T> {
rowsPerPage: number;
rows: T[];
page: number;
}
export const updatedRows = <T,>(args: IUpdatedRows<T>) => (args.rowsPerPage > 0
? args.rows.slice(args.page * args.rowsPerPage, args.page * args.rowsPerPage args.rowsPerPage)
: args.rows
);
interface IComponent1Row{
id: number;
qc: number;
// ...rest
}
interface IComponent2Row{
id: number;
name: string;
// ...rest
}
const rows1: IComponent1Row[] = [];
const rows2: IComponent2Row[] = [];
const updateRows1: IUpdatedRows<IComponent1Row> = {
page: 1,
rows: rows1,
rowsPerPage: 10
}
const updateRows2: IUpdatedRows<IComponent2Row> = {
page: 1,
rows: rows2,
rowsPerPage: 20
}
const updateRows1Result: IComponent1Row[] = updatedRows(updateRows1);
const updateRows2Result: IComponent2Row[] = updatedRows(updateRows2);
Link to the playground: link