21

Is it possible to have dynamic keys (prop names) in a jsdoc typedef? I'm imagining this would look something like the example below (which does not work).

@typedef {Object} Foo
@property {string} bar
@property {*} *

Passing properties not listed in the typedef e.g. {baz: 0} makes typescript upset with something like,

Argument of type '{ bar: string; baz: number; }' is not assignable to parameter of type 'Foo'. Object literal may only specify known properties, and 'baz' does not exist in type 'Foo'


Using the method proposed by @jcalz Object.<string, *> seems closer to the ideal output but resulted in a strange output

@typedef {Object} Foo
@property {number} bar
@property {Object.<string, *>}

output:

type Foo = {
    bar: number;
    (Missing): {
        [x: string]: any;
    };
}
3
  • Maybe use something like Object.<string, *> instead of Object, as mentioned here? Commented May 20, 2019 at 18:47
  • @jcalz, I wasn't able to make that work. I added the result to the post Commented May 21, 2019 at 12:34
  • 1
    Sorry, I've never really used JSDoc before. I was suggesting replacing Object in the first line with Object.<string, *>, and that works to add an index signature, but it breaks when you add bar. The only thing I have seen that works is /**@typedef { {[k: string]: any, bar: string } } Foo */, but that's basically just using TypeScript type syntax instead of JSDoc. Commented May 21, 2019 at 13:00

1 Answer 1

5

You can also use normal TS syntax in JSDOC.

See next example:

/**
 * 
 * @param {Record<string, string> & {bar:string}} arg
 */
const foo = (arg) => {}

You can even use utility types:

/**
 * 
 * @param {Partial<{age:number}>} arg 
 */
const partial = (arg) => { }

You can find more utils here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.