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:
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!
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"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With