objects-array filter and result just be object in typescript

To filter an array of objects in TypeScript and only return objects that meet certain criteria, you can use the filter() method. However, since TypeScript is a statically typed language, you'll need to use type assertions to ensure that the filtered array only contains objects of the desired type.

Here's an example:

index.ts
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const adultsOnly: Person[] = people.filter((person: Person) => {
  return person.age >= 18; // only return people who are 18 or older
});

console.log(adultsOnly);
337 chars
17 lines

In this example, we define an interface Person with name and age properties. We then define an array people with three objects that conform to the Person interface.

We then use the filter() method to create a new array adultsOnly, which contains only the objects from people where the age property is greater than or equal to 18.

We specify the callback function for .filter() to take a parameter of type Person, and we assert that the resulting adultsOnly array is also an array of type Person[].

This way, TypeScript knows that the resulting array only contains Person objects and can enforce type safety on any subsequent code that interacts with the array.

gistlibby LogSnag