kungfooman / RuntimeTypeInspector.js

Checking JSDoc types at runtime for high-quality types - Trust is good, control is better.
MIT License
8 stars 0 forks source link

src-transpiler/expandType.js: serialize IndexSignature #160

Closed kungfooman closed 3 weeks ago

kungfooman commented 3 weeks ago

Fixes: #155

This allows to structurize types like this:

/**
 * @param {{[n: number]: string, length: number}} words
 */
function countWords(words) {
  return words.length;
}
countWords({
  0: 'Hello',
  1: ' ',
  2: 'World',
  3: '!',
  length: 4
});
countWords(['Hello', ' ', 'World', '!']);

Into this:

/**
 * @param {{[n: number]: string, length: number}} words
 */
function countWords(words) {
  if (!inspectType(words, {
    "type": "object",
    "properties": {
      "length": "number"
    },
    "indexSignatures": [
      {
        "type": "indexSignature",
        "indexType": "string",
        "indexParameters": [
          {
            "type": "number",
            "name": "n"
          }
        ]
      }
    ],
    "optional": false
  }, 'countWords', 'words')) {
    youCanAddABreakpointHere();
  }
  return words.length;
}

The validation will happen in another PR...