Skip to content

Cannot use generics in JSDoc object signature #27215

Closed
@schmidtk

Description

@schmidtk

TypeScript does not appear to support using generics in JSDoc Object types (Object<string, T>). Doing so results in errors like Index signatures are incompatible. Type 'T' is not assignable to type 'string'..

TypeScript Version: 3.1.0-dev.20180919

Search Terms:

  • jsdoc object generic
  • object generic is not assignable to type
  • jsdoc object generic index signature

Code

/**
 * @param {T} val The value.
 * @return {Object<string, T>} The object.
 * @template T
 */
const createGenericObject = function(val) {
  return {
    'key': val
  };
};

/**
 * @const
 * @type {Object<string, string>}
 */
const myStringObject = createGenericObject('hello');

/**
 * @const
 * @type {Object<string, number>}
 */
const myNumberObject = createGenericObject(42);

Expected behavior:
No errors.

Actual behavior:

objectgeneric.js:16:7 - error TS2322: Type '{ [x: string]: T; }' is not assignable to type '{ [x: string]: string; }'.
  Index signatures are incompatible.
    Type 'T' is not assignable to type 'string'.

16 const myStringObject = createGenericObject('hello');
         ~~~~~~~~~~~~~~

objectgeneric.js:22:7 - error TS2322: Type '{ [x: string]: T; }' is not assignable to type '{ [x: string]: number; }'.
  Index signatures are incompatible.
    Type 'T' is not assignable to type 'number'.

22 const myNumberObject = createGenericObject(42);
         ~~~~~~~~~~~~~~

Playground Link: Not applicable (tsc behavior).

Related Issues: None found.

Metadata

Metadata

Assignees

Labels

DuplicateAn existing issue was already created

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions