ts-reset icon indicating copy to clipboard operation
ts-reset copied to clipboard

Fix the unsound parts of Object.values/Object.entries

Open guillaumebrunerie opened this issue 2 years ago • 4 comments

It's a great idea not to "fix" Object.keys as it is not broken, I fully support that! But you could push the reasoning further and actually fix the various broken parts of Object.values and Object.entries.

For instance it can introduce unexpected anys:

// Return type: any[] | null
const f = (x: unknown) => {
    if (x) {
        return Object.values(x);
    }
    return null;
}

// Return type: [string, any][] | null
const g = (x: unknown) => {
    if (x) {
        return Object.entries(x);
    }
    return null;
}

And it also does not respect structural typing and the possibility of having extra properties:

// Return type: number[], but x could have other properties with different types, should really be unknown[]
const h = (x: {a: number}) => Object.values(x);

// Return type: [string, number][] which is wrong in general for the same reason, should be [string, unknown][]
const i = (x: {a: number}) => Object.entries(x);

guillaumebrunerie avatar Feb 22 '23 22:02 guillaumebrunerie

https://github.com/niieani/nesity/tree/main/packages/types#fromentries

daniellwdb avatar Feb 23 '23 06:02 daniellwdb

Indeed, Object.fromEntries can also create unexpected anys (if that's what you mean), and should be fixed as well. The special case of constant readonly tuples seems extremely narrow, though, and not really worth it in my opinion.

guillaumebrunerie avatar Feb 23 '23 07:02 guillaumebrunerie