get dictionary/object keys as tuple in typescript
Asked Answered
M

3

27

I would like to get proper tuple type with proper type literals from an object in TS 3.1:

interface Person {
  name: string,
  age: number
}

// $ExpectType ['name','age']
type ObjectKeysTuple = ToTuple<keyof Person>

Why?:

To get proper string literals tuple when using Object.keys(dictionary)

I wasn't able to find a solution for this as keyof widens to union which returns ('name' | 'age')[] which is definitely not what we want.

type ObjectKeysTuple<T extends object> = [...Array<keyof T>]
type Test = ObjectKeysTuple<Person>
// no errors 🚨not good
const test: Test = ['age','name','name','name']

Related:

Mesothelium answered 27/11, 2018 at 16:14 Comment(1)
The union might be the best you can do here, unless you know for a fact that the order of the keys of dictionary is the same as the order of the keys declared in your interface, and you don't really know that. – Lodestone
L
23

The use case you're mentioning, coming up with a tuple type for Object.keys(), is fraught with peril and I recommend against using it.

The first issue is that types in TypeScript are not "exact". That is, just because I have a value of type Person, it does not mean that the value contains only the name and age properties. Imagine the following:

interface Superhero extends Person {
   superpowers: string[]
}
const implausibleMan: Superhero = { 
   name: "Implausible Man",
   age: 35,
   superpowers: ["invincibility", "shape shifting", "knows where your keys are"]
}
declare const randomPerson: Person;
const people: Person[] = [implausibleMan, randomPerson];
Object.keys(people[0]); // what's this?
Object.keys(people[1]); // what's this?

Notice how implausibleMan is a Person with an extra superpowers property, and randomPerson is a Person with who knows what extra properties. You simply can't say that a Object.keys() acting on a Person will produce an array with only the known keys. This is the main reason why such feature requests keep getting rejected.

The second issue has to do with the ordering of the keys. Even if you knew that you were dealing with exact types which contain all and only the declared properties from the interface, you can't guarantee that the keys will be returned by Object.keys() in the same order as the interface. For example:

const personOne: Person = { name: "Nadia", age: 35 };
const personTwo: Person = { age: 53, name: "Aidan" };
Object.keys(personOne); // what's this?
Object.keys(personTwo); // what's this?

Most reasonable JS engines will probably hand you back the properties in the order they were inserted, but you can't count on that. And you certainly can't count on the fact that the insertion order is the same as the TypeScript interface property order. So you are likely to treat ["age", "name"] as an object of type ["name", "age"], which is probably not good.


ALL THAT BEING SAID I love messing with the type system so I decided to make code to turn a union into a tuple in a way similar to Matt McCutchen's answer to another question. It is also fraught with peril and I recommend against it. Caveats below. Here it is:

// add an element to the end of a tuple
type Push<L extends any[], T> =
  ((r: any, ...x: L) => void) extends ((...x: infer L2) => void) ?
  { [K in keyof L2]-?: K extends keyof L ? L[K] : T } : never

// convert a union to an intersection: X | Y | Z ==> X & Y & Z
type UnionToIntersection<U> =
  (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

// convert a union to an overloaded function X | Y ==> ((x: X)=>void) & ((y:Y)=>void)     
type UnionToOvlds<U> = UnionToIntersection<U extends any ? (f: U) => void : never>;

// convert a union to a tuple X | Y => [X, Y]
// a union of too many elements will become an array instead
type UnionToTuple<U> = UTT0<U> extends infer T ? T extends any[] ?
  Exclude<U, T[number]> extends never ? T : U[] : never : never

// each type function below pulls the last element off the union and 
// pushes it onto the list it builds
type UTT0<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTT1<Exclude<U, A>>, A> : []
type UTT1<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTT2<Exclude<U, A>>, A> : []
type UTT2<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTT3<Exclude<U, A>>, A> : []
type UTT3<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTT4<Exclude<U, A>>, A> : []
type UTT4<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTT5<Exclude<U, A>>, A> : []
type UTT5<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? Push<UTTX<Exclude<U, A>>, A> : []
type UTTX<U> = []; // bail out

Let's try it:

type Test = UnionToTuple<keyof Person>;  // ["name", "age"]

Looks like it works.

The caveats: you can't do this programmatically for a union of arbitrary size. TypeScript does not allow you to iterate over union types, so any solution here will be picking some maximum union size (say, six consituents) and handling unions up to that size. My somewhat circuitous code above is designed so that you can extend this maximum size mostly by copying and pasting.

Another caveat: it depends on the compiler being able to analyze overloaded function signatures in conditional types in order, and it depends on the compiler being able to convert a union into an overloaded function while preserving order. Neither of these behaviors is necessarily guaranteed to keep working the same way, so you'd need to check this every time a new version of TypeScript comes out.

Final caveat: it has not been tested much, so it could be full of all sorts of πŸ‰ interesting pitfalls even if you keep the TypeScript version constant. If you are serious about using code like this, you'd need to subject it to lots of testing before even thinking of using it in production code.


In conclusion, don't do anything I've shown here. Okay, hope that helps. Good luck!

Lodestone answered 27/11, 2018 at 17:37 Comment(2)
I know about all the perils and ordering issue "guarantees". My use case was not just more deep but don't wanted to elaborate it here as it is not important :) question was rather how to get tuple from union :) Thx for extensive answer though, some beginners will find it very useful. cheers – Mesothelium
Just FYI: "Most reasonable JS engines will probably hand you back the properties in the order they were inserted, but you can't count on that." Yes, you can, provided none of the property names fits the definition of an integer index. This has been specified for some operations since ES2015, and for Object.keys since ES2017 or ES2018 (but that was just codifying the fact all major engines already provided the array in order). You probably shouldn't, but you can. :-) – Sapphera
E
18

Because of feedback i got on first and updated up to 18 union members version one can be simplified to this if you don't care about reversing...

And can handle objects instead of just object keys or any other type for that matter.

Enjoy.

/* helpers */
type Overwrite<T, S extends any> = { [P in keyof T]: S[P] };
type TupleUnshift<T extends any[], X> = T extends any ? ((x: X, ...t: T) => void) extends (...t: infer R) => void ? R : never : never;
type TuplePush<T extends any[], X> = T extends any ? Overwrite<TupleUnshift<T, any>, T & { [x: string]: X }> : never;
type UnionToIntersection<U> =(U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type UnionToOvlds<U> = UnionToIntersection<U extends any ? (f: U) => void : never>;
type PopUnion<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? A : never;
/* end helpers */
/* main work */
type UnionToTupleRecursively<T extends any[], U> = {
    1: T;
    0: PopUnion<U> extends infer SELF ? UnionToTupleRecursively<TuplePush<T, SELF>, Exclude<U, SELF>> : never;
}[[U] extends [never] ? 1 : 0]
/* end main work */

type UnionToTuple<U> = UnionToTupleRecursively<[], U>;

type LongerUnion = { name: "shanon" } | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
    | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18

declare const TestType: UnionToTuple<LongerUnion> // [18, 17, 16, 15, 14....]

Edit with latest version of typescript there's a newer more modern version, this new version relies on behaviour that is extremely unlikely to break in the future; where-as old implementation relied on behavior that was likely to change

type UnionToIntersection<U> = (
  U extends never ? never : (arg: U) => never
) extends (arg: infer I) => void
  ? I
  : never;

type UnionToTuple<T> = UnionToIntersection<
  T extends never ? never : (t: T) => T
> extends (_: never) => infer W
  ? [...UnionToTuple<Exclude<T, W>>, W]
  : [];


  type test = UnionToTuple<"1" | 10 | {name: "shanon"}>
  // ["1", 10, {name: "shanon"}]
Entebbe answered 25/4, 2019 at 23:12 Comment(4)
Did it break over the versions? It just shows const TestType: [x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never, x: never] – Cohabit
Hi kung iv'e added a edit with an example and newer simpler syntax – Entebbe
Thank you for your quick edit, its nice to learn functional programming from these non-trivial solutions. – Cohabit
holy sh*t, this is incredible – Roodepoortmaraisburg
E
10

@jcalz very impressive after reading your implementation i decided to write my own "N" recursive keys version this goes to infinite depth and keeps the ordering of the union I.E "A" | "B" becomes ["A", "B"]

// add an element to the end of a tuple
type Push<L extends any[], T> =
  ((r: any, ...x: L) => void) extends ((...x: infer L2) => void) ?
    { [K in keyof L2]-?: K extends keyof L ? L[K] : T } : never

export type Prepend<Tuple extends any[], Addend> = ((_: Addend, ..._1: Tuple) => any) extends ((
    ..._: infer Result
) => any)
    ? Result
    : never;
//
export type Reverse<Tuple extends any[], Prefix extends any[] = []> = {
    0: Prefix;
    1: ((..._: Tuple) => any) extends ((_: infer First, ..._1: infer Next) => any)
        ? Reverse<Next, Prepend<Prefix, First>>
        : never;
}[Tuple extends [any, ...any[]] ? 1 : 0];



// convert a union to an intersection: X | Y | Z ==> X & Y & Z
type UnionToIntersection<U> =
  (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

// convert a union to an overloaded function X | Y ==> ((x: X)=>void) & ((y:Y)=>void)     
type UnionToOvlds<U> = UnionToIntersection<U extends any ? (f: U) => void : never>;

// returns true if the type is a union otherwise false
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;

// takes last from union
type PopUnion<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? A : never;

// takes random key from object
type PluckFirst<T extends object> = PopUnion<keyof T> extends infer SELF ? SELF extends keyof T ? T[SELF] : never;
type ObjectTuple<T, RES extends any[]> = IsUnion<keyof T> extends true ? {
    [K in keyof T]: ObjectTuple<Record<Exclude<keyof T, K>, never>, Push<RES, K>> extends any[]
        ? ObjectTuple<Record<Exclude<keyof T, K>, never>, Push<RES, K>>
        : PluckFirst<ObjectTuple<Record<Exclude<keyof T, K>, never>, Push<RES, K>>>
} : Push<RES, keyof T>;

/** END IMPLEMENTATION  */



type TupleOf<T extends string> = Reverse<PluckFirst<ObjectTuple<Record<T, never>, []>>>

interface Person {
    firstName: string;
    lastName: string;
    dob: Date;
    hasCats: false;
}
type Test = TupleOf<keyof Person> // ["firstName", "lastName", "dob", "hasCats"]
Entebbe answered 28/2, 2019 at 2:36 Comment(5)
Whoa! Reverse<> is crazy! I had thought recursive types were impossible in typescript. I suspect using the core apparatus here, which can inductively manipulate arbitrary length tuples, could be bent to build a lot of algebraic types previously inaccessible in this language. I wonder if it provides a full workaround for the absent variadic parametric types feature? I see now that the way it works is based on infer obeying deferred type resolution, rather than eager: raw.githubusercontent.com/unional/typescript-guidelines/master/… – Tytybald
p.s., do not use TupleOf<> on very large unions, e.g. names of all the icons in FontAwesome -- it will make your compiler / linter / ide's language service hang for a long time while your CPU makes coffee. – Tytybald
Seems to break down around 7 or 8 elements in the union. Possibly the explicit enumeration of various depths is faster / more practical. :( – Tytybald
mmm i suspect if you sacrifice order should be able to go deeper, but the fact is there's no difference in compiler work between recursive and overloads (i believe) it only comes down to the fact that this solution has alot more loops. I think i can write a more performant one – Entebbe
It doesn't work with the last typescript version Type 'P' cannot be used to index type 'S'.(2536) (type parameter) S in type Overwrite<T, S extends unknown> – Erythrite

© 2022 - 2024 β€” McMap. All rights reserved.