1

Say I have a type test:

type test = {
    a: number,
    b: number,
    c: number,
    d: number,
}

How would I create a generic type that will extract a subset of test up to a specified key in the original order of the object, not including said key? For example:

type OrderedExtraction<T extends Object, K extends keyof T> = {.....?}

type subset = OrderedExtraction<test, "c"> 

> subset = {a: number, b: number}

I'm aware that ECMAScript technically makes no guarantees about the order of object keys (which would make this nonsensical), but unofficially V8 at least does seem to guarantee it.

Normally, one might do this using Omit, Pick, or Extract, but those won't work in this case unless a union of keys up to the specified one can be generated somehow. I suspect recursive types might be the way, but I'm not sure.

Dom C.
  • 11
  • 1
  • I personally wouldn't recommend using this. It causes a really hard time for the compiler. [This approach](https://tsplay.dev/NVRMZN) uses @jcalz answer in [this question](https://stackoverflow.com/questions/55127004/how-to-transform-union-type-to-tuple-type) where he explains why you shouldn't use such type. Anyway if it works for you, I'll write an answer explaining; If not, what am I missing? – wonderflame Jun 17 '23 at 23:49
  • Union orders are not stable in TypeScript so I wouldn’t even try to do this – jcalz Jun 18 '23 at 00:24
  • Do you have a guarantee that this type has keys added in the correct order? Like, `type A{a, b}; let B: A = {b, a}` will fail – Dimava Jun 18 '23 at 10:01
  • @wonderflame Absolute wizardry there. Shame union orders aren't stable... Do you think there's any way at all to maybe extract the first ordered key of an object? If there is seems to me a recursive conditional type could solve this pretty easily by just short-circuiting recursive eval once the target key is found. – Dom C. Jun 18 '23 at 19:30
  • @Dimava The type `test` in my example would be derived from an input object, so order parity should be guaranteed between the two. – Dom C. Jun 18 '23 at 19:34
  • Show a working (i.e. maybe in js) example. Without it it's impossible to check if that would work for you of 5-7 different cases ( https://tsplay.dev/empty ) – Dimava Jun 18 '23 at 19:37
  • @DomC. I'm not sure if there is an alternative to unions. And not sure how retrieve the first key in the object – wonderflame Jun 18 '23 at 19:51

0 Answers0