Home > Enterprise >  "T extends Component" in JSDoc
"T extends Component" in JSDoc

Time:08-17

get_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[]
{
    return this.components.filter(component => component instanceof component_type_to_return)
}

Here is an example of a method I wrote in TypeScript, what I am trying to do is make an equivalent version but with JSDoc.

** FINAL SOLUTION **

/**
 * Returns the components of type if the Doodad has one attached.
 * @template    {Component} T
 * @param       {{ new (doodad: Doodad): T }}   type    The component type to return     
 * @return      {T[]}                                   All components of given type attached to the Doodad
 */
get_components(type)
{
    return this.components.filter(component => component instanceof type)
}

CodePudding user response:

The following should do the trick:

Solution 1

/**
 * @type {{
 *   <T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[]
 * }}
 */
get_components(component_type_to_return)
{
    return this.components
      .filter(component => component instanceof component_type_to_return)
}

Solution 2

/**
 * @template {Component} T
 * @param {{ new (doodad: Doodad): T }} component_type_to_return
 * @returns {T[]}
 */
get_components(component_type_to_return)
{
    return this.components
      .filter(component => component instanceof component_type_to_return)
}
  • Related