1

In Typescript is it possible to convert the union of keys from a mapped type to a tuple?

For example, using the following type as the input:

{
    a: string; 
    b: number;
};

Can I output the type:

['a', 'b'];
Ryder Brooks
  • 2,049
  • 2
  • 21
  • 29
  • Do you mean `type Test = Foo<{ a: any, b: any }> // => "a" | "b"`? – tmhao2005 Nov 22 '20 at 17:56
  • No, I'm specifically looking for a fixed-length tuple of the keys – Ryder Brooks Nov 22 '20 at 18:02
  • 2
    Does this answer your question? [How to transform union type to tuple type](https://stackoverflow.com/questions/55127004/how-to-transform-union-type-to-tuple-type) – captain-yossarian from Ukraine Nov 22 '20 at 18:38
  • Sadly probably yes. I was hoping the changes allowing recursive conditional types in 4.1 could have opened the door for something – Ryder Brooks Nov 22 '20 at 18:46
  • Note that `{a: number, b: number}` and `{b: number, a: number}` are the same type, so I'm not sure how you expect `["a", "b"]` as opposed to `["b", "a"]`to come of that. Or would you be okay with `["a","b"] | ["b", "a"]`? If so there might be a different question that's a duplicate of – jcalz Nov 23 '20 at 02:13
  • 1
    i.e., [this one](https://stackoverflow.com/questions/58194653/use-tuple-instead-of-array-of-union-within-type) (see `UnionToAllPossibleTuples`) – jcalz Nov 23 '20 at 02:22
  • @jcalz for my use case order is not important. I upvoted your linked answer. Thank you. – Ryder Brooks Nov 23 '20 at 15:33

0 Answers0