Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This function has been copied from various projects, where it is common to transform an enum into another data structure. For instance: ``` enum InfuraNetworkType { mainnet = 'mainnet', goerli = 'goerli', sepolia = 'sepolia', } const infuraNetworkClientConfigurations = Object.keys(InfuraNetworkType).map((network) => { const networkClientId = buildInfuraNetworkClientId(network); const networkClientConfiguration = { type: NetworkClientType.Infura, network, infuraProjectId: this.#infuraProjectId, }; return [networkClientId, networkClientConfiguration]; }); ``` As the above example, one could use `Object.keys()` or even `Object.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. Both `Object.keys()` and `Object.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 merely `string[]`. 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 `getKnownPropertyNames` function which is like `Object.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 `network` would have a type of `InfuraNetworkType` and not `string`. Co-authored-by: Maarten Zuidhoorn <maarten@zuidhoorn.com>
- Loading branch information