Suppose that i have an object like:
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"}
]
I want to create a function to order by createdAt, which is the only field i'm sure it will be in the object. The function will be something like:
export const sortArrayByCreatedAt = (arr: TypeArr) => {
return arr.sort(function (a, b) {
return new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
});
};
How can i define the type of arr?
Type TypeArr {
createdAt: string
}
Is it good practice to define the type of the only known var?
I think that if someone else will see this function he will think that obj contains only createdAt, but i didn't find a better solution.
Array<A | B>. If both of these interfaces have thecreatedAtproperty, your code should compile just fine.interface TypeArr { createdAt: string; updatedAt?: string; animal?: string}andconst obj: TypeArr[] = [...]