Description
Bug Report
🔎 Search Terms
Generic pick on object, type part of object, deconstructing of pick shows all keys of object
🕗 Version & Regression Information
- This is a crash
- This first occured today when trying to make some generic object picker
- It was tested on TS 4.3.5 and 4.4.2
- It occures both in TypescriptPlayground and Visual Studio Code
- It decrease developer experience as deconstruction can't be used
⏯ Playground Link
Playground link with relevant code
💻 Code
// We can quickly address your report if:
// - The code sample is short. Nearly all TypeScript bugs can be demonstrated in 20-30 lines of code!
// - It doesn't use external libraries. These are often issues with the type definitions rather than TypeScript bugs.
// - The incorrectness of the behavior is readily apparent from reading the sample.
// Reports are slower to investigate if:
// - We have to pare too much extraneous code.
// - We have to clone a large repo and validate that the problem isn't elsewhere.
// - The sample is confusing or doesn't clearly demonstrate what's wrong.
interface Mapper<T = any, R = any> {
(arg: T): R;
}
function pick<O, T extends keyof O>(keys: T[], obj?: O): Pick<O, T>;
function pick<T>(keys: T[]): Mapper;
function pick<O, T extends keyof O>(keys: T[], obj?: O) {
const picker: Mapper<O, { [K in T]: O[T] }> = _obj => Object.entries(_obj).reduce((o, [key, val]) => {
if (keys.includes(key as T)) o[key as T] = val;
return o;
}, {} as Pick<O, T>);
return obj ? picker(obj) : picker;
}
const { a, b } = pick(['b'], { a: 'a', b: 'b' }) //here the autosuggest should show b only
const obj = pick(['b'], { a: 'a', b: 'b' })
obj.a // here it is working properly as you can only select b
🙁 Actual behavior
When using the deconstruction construction after pick, I can select b as well as a. But the a is not in object returned from pick.
When first assigning the return value to const, in later code I can only select b, which is expected.
🙂 Expected behavior
In deconstruction I should be able to select only keys, that I declared in pick function. The behaviour should be same as in second example, where the return object is first assigned to obj
var and then refered.