Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

get dictionary/object keys as tuple in typescript

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...