0

I am learing TypeScripe, and I am trying to make some util ts types.

For example:

I now have an interface like this:

interface Student{
  name: string,
  id: number,
  gender: string
 }

and I am need to get the keys to form a new Array type like this

type Arr = ['name', 'id', 'gender']

so how can I write an util type to make that happen.

  • That's a _tuple_ type. Do you just want `keyof Student`, the string literal type? Or something else? How would you use it? – jonrsharpe May 08 '23 at 16:42
  • We definitely need more details and clarity here around what you intend to do. – jcalz May 08 '23 at 16:44

1 Answers1

1

I think what you're looking for is this: https://stackoverflow.com/a/55128956. You can also find other solutions here https://github.com/microsoft/TypeScript/issues/13298.

In your case, you need to use the keyof keyword to get a union of the keys (keyof Student), and then you pass it to the TupleUnion helper. Keep in mind that the order of the literal values in the union isn't always guaranteed.

https://tsplay.dev/Nr922w

Pedro Durek
  • 303
  • 4
  • 18
  • There's a HUGE DISCLAIMER on the linked answer that this is a bad idea, and there are explanations in there about why. Please [edit] your answer to acknowledge that this is a bad idea, or that they at least need to be very careful. – jcalz May 08 '23 at 17:21
  • Hey @jcalz, I've been using this approach for some time now, and it works perfectly for string literals. Unfortunately, up until now, there is no easy way to perform this task, you can find other solutions here https://github.com/microsoft/TypeScript/issues/13298, but they're all similar... I don't feel the need to acknowledge that this is a "bad idea" since I'm already linking the official solution that already communicates that. – Pedro Durek May 08 '23 at 18:34
  • Show me it "working perfectly" and I'll break it. [Here is an example](https://tsplay.dev/N7qbBW). Would you please edit as I asked? Or is there some principled reason why you won't other than "I don't need to"? – jcalz May 08 '23 at 18:40
  • that's because it creates the tuple starting from the last element in the union, we can't guarantee the order of the tuple, but we can guarantee each element to be declared once. I'll update my answer for a slightly better solution (that starts with the first element in the union). – Pedro Durek May 08 '23 at 18:49
  • yep, I did not know it was this difficult. But this is exactly what I want.. – skyScraperno_1 May 09 '23 at 17:30