type-challenges icon indicating copy to clipboard operation
type-challenges copied to clipboard

17973 - DeepMutable

Open jiangshanmeta opened this issue 3 years ago • 4 comments

type DeepMutable<T extends Record<keyof any,any>> =
  T extends (...args:any[])=>any?
    T:
    {
      - readonly [K in keyof T]:DeepMutable<T[K]>
    }

jiangshanmeta avatar Oct 29 '22 14:10 jiangshanmeta

Why we can use DeepMutable<T[K]> directly? T[k] can be primitive, and why it doesn't tigger the generic constraint T extends Record<keyof any, any>?

BruceYuj avatar Aug 02 '23 16:08 BruceYuj

Why we can use DeepMutable<T[K]> directly? T[k] can be primitive, and why it doesn't tigger the generic constraint T extends Record<keyof any, any>?

because T[K] extends any ?

sv-98-maxin avatar Sep 20 '23 07:09 sv-98-maxin

@BruceYuj question is valid.

T[k] can be primitive, and why it doesn't tigger the generic constraint T extends Record<keyof any, any>?

I've got the same question. How is this possible?

@sv-98-maxin T[K] extends any only inside Record. When T[K] is not a Record but a primitive value instead like string, then what's actually going on?

kstratis avatar May 02 '24 10:05 kstratis

@BruceYuj Turns out the answer to ~your~ our question is this:

Mapped types already "skip" primitives by returning the input, and they automatically distribute over union, so you don't need to check for these yourself

Example:

type Look<T> = { [K in keyof T]: 123 };
type Y1 = Look<{ a: string }> // {a: 123}
type Y2 = Look<string> // string
type Y3 = Look<{ a: string } | { b: string }>
//  Look<{ a: string; }> | Look<{ b: string; }>

For the full story have a look at this great SO post: https://stackoverflow.com/questions/68693054/what-is-extends-never-used-for/68693367

kstratis avatar May 02 '24 10:05 kstratis