Let's say we have an object structured as follows:
const obj = [
{ createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"},
{ createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"}
]
We want to develop a function that arranges the objects by the "createdAt" field, which is guaranteed to exist in each object. The function prototype would look like this:
export const sortArrayByCreatedAt = (arr: TypeArr) => {
return arr.sort(function (a, b) {
return new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
});
};
How should we define the type of the 'arr' parameter?
Type TypeArr {
createdAt: string
}
Is it considered best practice to specify the type of the only known variable?
In my opinion, when someone else looks at this function, they might assume that the 'obj' array solely consists of objects with the 'createdAt' property. However, I couldn't come up with a better alternative.