microsoft / microsoft/TypeScript

JSDoc `@overload`s on constructors don't capture class type parameters, can dictate their return type

Open
#55,919 7 comments 1 reaction 1 assignee View on GitHub

@sandersn is already working on this.

Since Sep 29, 2023.

checkJs Domain: JavaScript Domain: JSDoc Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Found from #55916.

Today if you try to write a generic constructor, captured type parameters fail to create a generic signature. Instead, the type parameter is effectively leaked and never instantiated.

/**
 * @template T
 */
class C {
    /**
     * @overload
     * @param {T} value
     */

    /**
     * @overload
     * @param {T} first
     * @param {T} second
     */

    /**
     * @param {T} first
     * @param {T} [second]
     */
    constructor(first, second) {
    }
}

const x = new C(123);
//              ~~~
// Argument of type 'number' is not assignable to parameter of type 'T'.
//  'T' could be instantiated with an arbitrary type which could be unrelated to 'number'.

const y = new C("hello", "world");
//              ~~~~~~~
// Argument of type 'string' is not assignable to parameter of type 'T'.
//  'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.

The current-workaround is to write something like the following:

/**
 * @template T
 */
class C {
    /**
     * @template T
     * @overload
     * @param {T} value
     * @return {C<T>}
     */

    /**
     * @template T
     * @overload
     * @param {T} first
     * @param {T} second
     * @return {C<T>}
     */

    /**
     * @param {T} first
     * @param {T} [second]
     */
    constructor(first, second) {
    }
}

const x = new C(123);
//    ^?

const y = new C("hello", "world");
//    ^?

const y = new C(123, "hello");
//    ^?

Notice that here, each @overload must declare its own type parameters and return type.

We should decide if this is actually how we want @overload to work in JSDoc on constructor declarations.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.