jsdoc typedef based on real const

Viewed 61

for example i have const and typedef for it

/**@typedef {{key1:string,key2:string,key3:string}} optionsType*/
const options = {
  key1: "val1",
  key2: "val2",
  key3: "val3"
};

and then i want write function that require any key fo "options" object as parameter

/**
 * @param {keyof optionsType} key
 */
function func(key){
/* ... */
 return 0
}

but later, if i want change pool of available keys i need to change object itself and typedef for it.

Is it possible to avoid that and declare type based on object itself?

1 Answers

Yes, it's possible. Take a look at the following snippet.

const options = {
  key1: "val1",
  key2: "val2",
  key3: "val3"
};

/**
 * @typedef {typeof options} optionsType
 */

In between { and } in the @typedef you can write any valid typescript code.

Related