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.ts337 chars17 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