In this scenario, I am developing a utility function with the objective of dynamically sorting an array of objects (the first parameter) in alphabetical order, based on a specified key
passed as the second argument.
The utility function is defined as follows:
interface GenericObject {
[key: string]: string;
}
export const sortAlphabetically = (array: Array<GenericObject>, sortBy: keyof GenericObject) => {
let isKeyValid = false;
// check if the key exists in the object before attempting to sort by it
if (array.length > 0) {
isKeyValid = array.every(obj => Object.prototype.hasOwnProperty.call(obj, sortBy) && typeof obj[sortBy] === 'string');
}
if (isKeyValid) {
array.sort((a: GenericObject, b: GenericObject) =>
a[sortBy].toLowerCase() < b[sortBy].toLowerCase()
? -1
: a[sortBy].toLowerCase() > b[sortBy].toLowerCase()
? 1
: 0,
);
return array;
} else {
return;
}
};
At this stage, prior to testing the function, if I attempt to run:
export interface Person {
name: string;
surname: string;
}
const people: Person[] = [
{name: 'John', surname: 'Smith'},
{name: 'Tony', surname: 'Denver'},
{name: 'Mary', surname: 'Howard'},
]
sortAlphabetically(people, 'name');
or this:
export interface Car {
model: string;
make: string;
}
const cars: Car[] = [
{model: 'Golf', make: 'Volkswagen'},
{model: 'X1', make: 'BMW'},
{model: 'Clio', make: 'Renault'},
]
sortAlphabetically(cars, 'make');
An error is encountered:
TS2345: Argument of type 'Person[]' is not assignable to parameter of type 'GenericObject[]'. Type 'Person' is not assignable to type 'GenericObject'. Index signature is missing in type 'Person'.
A similar issue arises for Car[]
.
As a utility function, it is essential for it to be able to handle any
type of object within the array, without triggering type errors.
I suspect the issue lies in the way I am defining my GenericObject
.
Could someone provide guidance on what I might be overlooking here? Thank you.