sindresorhus / type-fest

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

`Proposal`: add option with exclude/keep specified type on deep type #862

Open Emiyaaaaa opened 3 months ago

Emiyaaaaa commented 3 months ago

Look at this scene

I have a type Item that wrapped with some util type, and I want get a simplify Item, like:

import type { SimplifyDeep } from 'type-fest/source/merge-deep'

type SimplifyItem = SimplifyDeep<Item>
// => expect type SimplifyItem = { name: string, color: THREE.Color }

but actual rsult is:

import type { SimplifyDeep } from 'type-fest/source/merge-deep'

type SimplifyItem = SimplifyDeep<Item>
/**
type SimplifyItem = { 
    name: string,
    color: {
            readonly isColor: true;
            r: number;
            g: number;
            b: number;
            set: (color: string | number | Color) => Color;
            ... 31 more ...;
            toArray: {
                ...;
            };
        };
}
*/

so maybe we can add a exclude type option ( or named keep ) on Deep type like:

import type { SimplifyDeep } from 'type-fest/source/merge-deep'

type SimplifyItem = SimplifyDeep<Item, { exclude: THREE.Color }>
// => expect type SimplifyItem = { name: string, color: THREE.Color }

It can also resolve scene conflicts between users, such as one want recursive into HTMLElemet, anther one want keep HTMLElemet

Related comment: https://github.com/sindresorhus/type-fest/issues/651#issuecomment-1803324362 Related issue: #651

Upvote & Fund

Fund with Polar

voxpelli commented 3 months ago

One could also do:

type SimplifyItem = SimplifyDeep<Omit<Item, 'color'>> & Pick<Item, 'color'>;

And if one wants a helper to keep it a bit shorter one could do something like this in ones types:

type SimplifyDeepExcept<A, B extends keyof A> = SimplifyDeep<Omit<A,B>> & Pick<A, B>;

Is it common that that needs to exclude something like THREE.Color at an unknown location in an object?

voxpelli commented 3 months ago

Related: https://github.com/sindresorhus/type-fest/issues/719

Kind of requests the opposite: https://github.com/sindresorhus/type-fest/issues/860 (Kind of request an { only: string } rather than an { exclude: string })

Emiyaaaaa commented 3 months ago
type SimplifyItem = SimplifyDeep<Omit<Item, 'color'>> & Pick<Item, 'color'>;

My case is more complicated. THREE.Color is deep in nested object, and must used type to exclude not key, because key could be 'lineColor', 'pointColor' or other in my scene

sindresorhus commented 3 months ago

This proposal makes sense to me.

Emiyaaaaa commented 2 months ago

Sorry, I found I could use ConditionalSimplifyDeep<Item, THREE.Color, object> instead, but other deep type also need this feature.