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 only use a subset of the fields of an object, but also return the original object?

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.

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

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')

Playground Link

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