1

I have the

enum EthereumNetwork {
  MAIN_NET,
  ROPSTEN,
  KOVAN
}

class EthereumHDWallet {
  constructor(network: EthereumNetwork) { }
}

The task is to write a test which goes over all possible networks and trying to create EthereumHDWallet. Something like that:

  for (const network in EthereumNetwork) {
      const wallet = new EthereumHDWallet(network);
      it('constructor', () => {
        expect(wallet).toBeDefined();
      });
  }

Unfortunately, the code above doesn't work because of error TS2345: Argument of type 'string' is not assignable to parameter of type 'EthereumNetwork'. Does anyone know way around?

2
  • It's important to point out that enums in TypeScript boil down to both the numeric index and the string representation. That's what you're seeing in the examples you've provided. Commented Jul 3, 2019 at 22:27
  • turned out, the example I've provided doesn't actually work either. Commented Jul 3, 2019 at 22:39

1 Answer 1

1

Iterating over all the keys will give you too much (it will also give you the keys "0", "1", "2"). You can filter it down and get the type-safety you want, but you have to tell TypeScript that this is safe (with the as K[] in enumKeys below):

function enumKeys<O extends object, K extends keyof O = keyof O>(obj: O): K[] {
  return Object.keys(obj).filter(k => Number.isNaN(+k)) as K[];
}

for (const networkName of enumKeys(EthereumNetwork)) {
  const network = EthereumNetwork[networkName];
  const wallet = new EthereumHDWallet(network);
}
Sign up to request clarification or add additional context in comments.

2 Comments

this is excellent! Is there any reason why TypeScript shouldn't treat operators "for in" and "for of" in a similar way out of the box for enums?
for ... of they could (because the generated enum could implement the iterator protocol), but they can't change for ... in behavior with enums without more runtime emit (which is counter to the design goals of the language)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.