sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.15k stars 535 forks source link

Key Inference for `Merge` and `MergeDeep` #958

Open SaintPepsi opened 2 weeks ago

SaintPepsi commented 2 weeks ago

I'm not sure if this is even possible in, but would doesn't hurt to ask I reckon. Would it be possible to have the second parameter for Merge and MergeDeep have the keys of the type you're passing into it be provided as possible overrides/restrictions?

type Foo = {
    foo: string;
    bar: {
        baz:  number
    }
};

type MergedType = Merge<Foo, { baz: string } >; // <-- `baz` would cause an error because the key does not exist on `Foo`
type MergedType = MergeDeep<Foo, { bar: { foo: number } } >; // <-- `bar.foo` would cause an error because the key `foo` does not exist on `Foo['bar']`

We've built an automated type harvesting system that collects a lot of type data to be used by the frontend and sometimes we have to correct those types deeply

At the moment Merge works as expected, but if any of the types for the response data changes we don't know that because Merge does not care whether or not the second argument matches the structure of the first.

Also apologies if this already exists, there's so many types in this library I can't wrap my head around all of them.

Upvote & Fund

Fund with Polar

sindresorhus commented 2 weeks ago

It may be possible, but should be separate types from Merge. Maybe something called MergeStrict or MergeExact.

SaintPepsi commented 2 weeks ago

What would be a starting point? I've only really done string inference.