Pick keys from object in TypeScript
Selects keys from an object and gets a correctly narrowed type back.
function pick<T extends object, K extends keyof T>(
obj: T,
keys: K[],
): Pick<T, K> {
const out = {} as Pick<T, K>;
for (const key of keys) {
if (key in obj) {
out[key] = obj[key];
}
}
return out;
}
Keywords and builtins used here
KTasconstextendsforfunctionifofreturn
The run, in numbers
- Lines
- 12
- Characters to type
- 199
- Tokens
- 76
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 43 seconds.
Step 1 of 11 in Generic helpers, step 9 of 20 in Generics.