0

I'm using a 3rd party library that has defined a type like this:

type DefaultButtons = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H';

there is a function that I can call that lets me remove buttons, and it has an api that looks like this:

removeDefaultButtons( buttonsToRemove : DefaultButtons[] );

In my code I know that I would like to keep (say) 'A', 'D' and 'G' but remove all the rest.

Therefore, I'd like to do something like this:

const buttonsToKeep : DefaultButtons[] = ['A', 'D', 'G'];

const allPossibleButtons : DefaultButtons[] = ?? //how to populate this

const removeButtons = allPossibleButtons.filter( b => buttonsToKeep.includes( b ) );
removeDefaultButtons( removeButtons );

The problem is that I'm not sure how I can populate the allPossibleButtons array from the string literal type?

Marek Krzeminski
  • 1,308
  • 3
  • 15
  • 40
  • https://stackoverflow.com/questions/44480644/typescript-string-union-to-string-array does not answer my question. In that question the poster wants to convert an array to a type. I want the complete opposite. I have a type, but want to get an array. – Marek Krzeminski Dec 19 '19 at 19:28
  • Doesn't the `getAllStringUnionValues` function from the question poster code in the linked post do, what you are trying to achieve (string literal union type -> tuple)? – ford04 Dec 19 '19 at 19:55
  • If I'm understanding the getAllStringUnionValues function, it looks like that function needs to be called by passing in an object containing the keys that match a particular type. I don't even have such an object in my case. All I have is a string literal type defined for DefaultButtons. I want to be able to extract all the strings from this type, and put them in an array. – Marek Krzeminski Dec 19 '19 at 20:03
  • Yeah, you would have to create the object literal from the type constraint manually so that it is also existent at run-time, as types get lost after compilation. I think, that is the general way to go here (was about to post an answer similar to the linked OP question code). – ford04 Dec 19 '19 at 20:12
  • The question this duplicates specifically asks for a way to take a type and generate an array from it, like you're asking. The answer is that you can't do that, the type system is erased. Instead, you can do the reverse: make an array and generate your type from it. If that doesn't suit your needs, then there's not much to say; you can't generate runtime code from types. – jcalz Dec 19 '19 at 21:43

0 Answers0