Add getKnownPropertyNames #111
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This function has been copied from various projects, where it is common to transform an enum into another data structure. For instance:
As the above example shows, one could use
Object.keys()or evenObject.getOwnPropertyNames()to obtain said properties. A problem occurs, however, if the type of the properties of the resulting object needs to match the type of the properties in the enum, that means the variable inside the loop needs to be of that type, too. BothObject.keys()andObject.getOwnPropertyNames()are intentionally generic: they returns the property names of an object, but neither can make guarantees about the contents of that object, so the type of the property names is merelystring[]. While this is technically accurate, we don't have to be so cautious in these situations, because we own the object in question and therefore know exactly which properties it has.This commit adds a
getKnownPropertyNamesfunction which is likeObject.getOwnPropertyNames()except that the resulting array of property names will be typed using the types of the properties of the given object. In the above example that would mean that the type ofnetworkwould be a type union of the keys ofInfuraNetworkTypeand notstring.