Our API is designed to handle a large amount of data, allowing users to control which properties are returned by using the fields
parameter. The API definition looks like this:
interface Foo {
A?: string;
B?: number;
C?: boolean;
D?: string[];
E?: number[];
}
Throughout our codebase, we often see patterns like this:
// simplified project-specific type definition
interface MyFoo {
A?: string;
C?: boolean;
}
const fields = ['A', 'C'];
...
const myFoo = await axios.get(... some URL with "fields" parameters ...) as MyFoo;
To streamline and reduce the risk of errors, I want to consolidate everything based on the main API definition. This involves creating a new type using the keys from the Foo interface and incorporating that array into the API call.
This is what I have so far:
declare function getFoo<T extends Foo, K extends keyof T>(fields: K[]): Pick<T, K>;
This approach gets me most of the way there:
const myFoo = getFoo(['A', 'C']);
type MyFoo = typeof myFoo; // type MyFoo = { A?: string; C?: boolean }
However, I am wondering if there is a more efficient way to achieve this without the need for a two-step process?
I attempted something like ReturnType<typeof getFoo>
but it retrieves the whole original definition since there doesn't seem to be a way to pass the fields array into it.