hegemonic / catharsis

A JavaScript parser for Google Closure Compiler and JSDoc type expressions.
MIT License
54 stars 14 forks source link

What's the correct way to annotate arrays of objects? #46

Closed Madd0g closed 7 years ago

Madd0g commented 8 years ago

I found this on stack overflow, but it doesn't work:

  * @param {{name:string, email:string}[]} users

I tried this, and it works:

* @param {Array<{name:String, email:String}>} users

it returns this in applications:

{
  "type": "RecordType",
  "fields": [
    {
      "type": "FieldType",
      "key": {
        "type": "NameExpression",
        "name": "name:String"
      }
    },
    {
      "type": "FieldType",
      "key": {
        "type": "NameExpression",
        "name": "email:String"
      }
    }
}

Is that the recommended way to document nested objects? Or is there something that would further parse the email/string and name/string combinations into their own properties?

EDIT: this stackoverflow answer suggests doing it like this:

* @param {Object[]} users
* @param {string} users[].name - user name
* @param {string} users[].email - user email

Thanks!

hegemonic commented 7 years ago

Sorry for the lengthy delay in responding to this.

Yes, the Stack Overflow answer you cited is a good way of handling this in JSDoc. You can also use @param {Array<{name: string, email: string}>} users (note the spaces), which gives you this parse result from Catharsis:

{
  "type": "TypeApplication",
  "expression": {
    "type": "NameExpression",
    "name": "Array"
  },
  "applications": [
    {
      "type": "RecordType",
      "fields": [
        {
          "type": "FieldType",
          "key": {
            "type": "NameExpression",
            "name": "name"
          },
          "value": {
            "type": "NameExpression",
            "name": "string"
          }
        },
        {
          "type": "FieldType",
          "key": {
            "type": "NameExpression",
            "name": "email"
          },
          "value": {
            "type": "NameExpression",
            "name": "string"
          }
        }
      ]
    }
  ]
}