I have a simple function that takes an array of objects. In this function, I only use the status field and don’t care about any of the other fields.
export const filterActiveAccounts = ({
accounts,
}: {
accounts: Array<{ status: string; }>;
}) =>
accounts.filter(({ status }) => status === 'active')
When I use this, I want it to return the same object type as what was passed in. What I mean is I should be able to do 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, given the current definition of filterActiveAccounts, the return type is of type Array<{ status: string; }>, so this would cause Typescript to throw an error.
I have a gut feeling I need to use generics, but am not sure how to write it.
>Solution :
You just need to add a type parameter to the function in order to capture the actual type passed in. The return type will then be inferred to be the same type as the type passed in:
export const filterActiveAccounts = <T extends { status: string; }>({
accounts,
}: {
accounts: Array<T>;
}) =>
accounts.filter(({ status }) => status === 'active')