-2

I cannot evaluate a property inline in a nested dictionary. If I evaluate the property into a separate local variable, it works. Why is that?

This throws an error

const appConfig = {
  config.networks!.testnet?.chainId! : {
    "token1": "mytoken"
  }
};

This works

const chainId = config.networks!.testnet?.chainId!;
const appConfig = {
   chainId : {
    "token1": "mytoken"
  }
};
siamii
  • 23,374
  • 28
  • 93
  • 143

1 Answers1

1

Because you forgot the brackets
... in BOTH cases

const appConfig = {
  [config.networks!.testnet?.chainId!] : {
    "token1": "mytoken"
  }
};
const chainId = config.networks!.testnet?.chainId!;
const appConfig = {
   [chainId] : {
    "token1": "mytoken"
  }
};

Typescript is not Python, chainId key means string "chainId" key

Also you can only have string (and number, and symbol) keys (everything else (including numbers) is cast to string)
If you need to use objects as keys, use new Map<KeyType, ValueType>(pairs: [KeyType, ValueType][])

Dimava
  • 7,654
  • 1
  • 9
  • 24
  • thanks, so why is the second one not throwing error then? the one with the local variable – siamii Aug 30 '23 at 20:07
  • @siamii because it's `const appConfig = { "chainId" : { "token1": "mytoken" } };` (`chainId` interpreted as literal string key) . It would still work if you delete the line with variable – Dimava Aug 30 '23 at 20:08