Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: How to define only one type of javascript object

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

I would define my TypeArr as an interface and the sort method as a generic method. So it wouldn’t change the return type.

export const sortArrayByCreatedAt = <T extends TypeArr>(arr: Array<T>) => {
    return arr.sort(function (a, b) {
        return new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
    });
};

interface TypeArr{
    createdAt :string
}

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"}
]

const sorted = sortArrayByCreatedAt(obj);

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading