0

consider the following code snippet:

let proposals = JSON.parse(fs.readFileSync(proposalsFile, "utf8"))
proposals[network.config.chainId!.toString()].push(proposalId.toString())
fs.writeFileSync(proposalsFile, JSON.stringify(proposals))

The initial proposalFile contains the following: { '31337': [] }

I don't understand what is happening in the second line above. How can the index of the array proposals[] be of type String, if indeed it is an array?

What is the meaning of the ! in ChainId!?

Subsequent executions of this script will result in strings getting appended in the proposalFile:

{"31337":["21810620491323861737494108894072031792136914678422989467418569109597477706871","21810620491323861737494108894072031792136914678422989467418569109597477706871"]}

I understand why this is done, I don't understand how the code snippet results in the above JSON file? The original context of this snippet can be found here: https://github.com/PatrickAlphaC/dao-template/blob/main/scripts/propose.ts

TylerH
  • 20,799
  • 66
  • 75
  • 101
maskara
  • 329
  • 1
  • 2
  • 12
  • 1
    `proposals` is not an array, it's an object. The index is a string like `'31337'` – Barmar Apr 11 '22 at 18:17
  • Notice the `{}` around it. That makes an object. Arrays are delimited with `[]`. – Barmar Apr 11 '22 at 18:19
  • 1
    Re: what is the meaning of `!` - https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci – James Apr 11 '22 at 18:21
  • 1
    @Barmar Does he not access it with a string `proposals[network.config.chainId!.toString()]` ? That part seems fine. And as the other comment explains, the exclamation mark in `chainId!` simply tells typescript we know this will never be null. I'm not clear why there is an extra wrapping `{}` when saving the JSON though. – ᴓᴓᴓ Apr 11 '22 at 18:23
  • 1
    @ᴓᴓᴓ Right. `proposals` is an object, and `network.config.chainId` is an ID like `31337`. There's no need to call `.toString()` explicitly; object property names are automatically converted to strings. I also don't see where the extra `{}` wrapper comes from. Maybe that's a copying error by the OP. – Barmar Apr 11 '22 at 18:27
  • I apologize, the extra wrapping{ } was a typo and has been edited out. I'm still processing the other comments. Thanks all! – maskara Apr 11 '22 at 19:01
  • 1
    Read about [accessing object properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Accessing_properties) in the [JavaScript documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/). – axiac Apr 11 '22 at 19:04
  • thanks all. now I get it...! Object properties can be accessed by using the dot notation or the bracket notation and that's what I was struggling with ! – maskara Apr 11 '22 at 19:11

0 Answers0