I have a straightforward function that works with an array of objects. The function specifically targets the status
field and disregards all other fields within the objects.
export const filterActiveAccounts = ({
accounts,
}: {
accounts: Array<{ status: string; }>;
}) =>
accounts.filter(({ status }) => status === 'active')
My aim is for the function to return the same type of object as the one passed in. This means I should be able to use it like this:
type FoobarAccount {
status: string;
baz: string;
lorem: string;
}
const foobarAccounts = [
{ status: "active", baz: "xxx", lorem: "xxx" },
{ status: "pending", baz: "xxx", lorem: "xxx" },
]
const active_accounts: Array<FoobarAccount> = filterActiveAccounts({ accounts: foobarAccounts })
However, the current definition of filterActiveAccounts
results in a return type of Array<{ status: string; }>
, which triggers a Typescript error in this scenario.
My intuition tells me that I may need to utilize generics, but I'm uncertain about how to implement them.