Let's say that I have the following payload:
{a: 1, b: 2, c: 3}
And I want to have a function that, given an object, picks some keys and returns a type accordingly.
function pick<T>(obj: any, ...keys: string[]): T {
return (
Object.fromEntries(
keys
.filter(key => key in obj)
.map(key => [key, obj[key]])
)
) as T;
}
const test = { a: 1, b: 2, c: 3 };
type Foo = {
a: number,
b: number
}
const result = pick<Foo>(test, 'a', 'b');
console.log(result);
Is there a way to handle this better? I understand that using type coercion is pretty much shutting down Typescript safety-net.
For example, if I do this:
console.log(pick<Foo>(test, 'b'));
I am telling typescript that the function pick returns a Foo object, yet it doesn't have the key a defined.
The use case is that we have API calls that we:
- Have to type
- Only want to type the relevant keys for our use case
- Do it following TS best practices