Skip to content

pick: pick should return Partial<Pick<T,K>> #1623

@florian-lackner365

Description

@florian-lackner365

tl;dr: pick should return Partial<Pick<T,K>>. It might be possible to specialize to Pick<T,K> for certain types K. Would you be willing to accept a contribution?

Consider this code:

const t = { a: 1, b: 2, c: 3 };
type T = typeof t;
const k = [Math.random % 2 === 0 ? 'a' : 'b'] as const; // readonly ['a' | 'b']
const res = pick(t, k); // Pick<T, 'a' | 'b'>
// but res === { a: 1 } or { b: 2 } <-> Pick<T, 'a'> | Pick<T, 'b'>

The easy solution to fix this would be to return Partial<Pick<T, K>> from pick. However, that's annoying for situations where we know that all Ts are going to be in K, like: pick(x, ['a', 'b']). In this case we want Pick<X, 'a' | 'b'>.

The fix in TS seems to be complicated though. I tried a little bit and got tuple detection to work. I could prepare a PR that would fix the type for general arrays to Partial<Pick<T, K>> and to Pick<T, K> if the user passes a tuple. That would deblock a common case, while still being wrong in the example I gave.

What do you think? Would you be willing to accept such a contribution? Do you prefer the status quo?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions