3

In Typescript, you'd just do this:

class Test {
  [key: string]: whatever
}

Which allows you to access computed property names like so...

class Test {
  getProp(key) {
    return this[key]
  }
}

... without receiving Element implicitly has an 'any' type because type 'Test' has no index signature.

I can't figure out how to accomplish the equivalent with JSDoc. Anyone had any luck with this?

hbauer
  • 94
  • 7
  • Yep, so with a normal object you'd just do: `/** @type {{ [key: string]: string }} */` `const obj = { key: 'string' }` – hbauer Feb 26 '22 at 04:13
  • Nah, it definitely falls under more obscure usage. I thought https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html would cover it but no dice. – hbauer Feb 26 '22 at 04:17
  • Note: I'm using JSDoc not primarily for documentation but for type-checking in JS – hbauer Feb 26 '22 at 04:18
  • Why do you need to store or access dynamic property names on the class – kelsny Feb 26 '22 at 04:43
  • Scenario: I pass in a parameter to the constructor that's an object with many keys/values. I want to then assign those properties directly to the class so that the end-user doesn't have to do `Test.object.property` and can simply do `Test.property`. – hbauer Feb 26 '22 at 16:59

1 Answers1

2

For a single method, it's possible to do this with the @this tag:

class Test {
    /**
     * @this {{[k: string]: string}}
     * @param {string} key
     */
    getProp(key) {
        return this[key]
    }
}

Doing it for the entire class isn't yet supported. There is an open feature request (TypeScript#48096) which is currently in the TS 4.7.1 milestone. However, given the Needs Proposal label, somebody needs to come up with a proposed JSDoc tag + syntax, or it will likely end up being pushed off that milestone.

Gerrit0
  • 7,955
  • 3
  • 25
  • 32
  • This looks pretty canonical to me. Thanks for pointing us to ward an official source. – JDB Apr 20 '22 at 15:35