microsoft / microsoft/TypeScript

[Regression] TS2562 - mixins cannot accept generic types

Open
#24,122 7 comments 39 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 2.6.0 and more

Search Terms: mixin, 2.6.

Code

export interface Constructor<T = any> extends Function {
  new(...args: any[]): T;
}

class A<T> {
  public a: T;
}

class B<T> {
  public b: T;
}

function Mixin<T>(...classes: any[]): Constructor<T> {
  return function() {
    // whatever, not the purpose of the demonstration
  } as any;
}

interface IAB<T, U> extends A<T>, B<U> {}
// on typescript 2.6.0 and more, its no more possible to use generic types into mixins....
class AB<T, U> extends Mixin<IAB<T, U>>(A, B) {
}

// on typescript 2.6.0 we're forced to write
// class AB<T, U> extends Mixin<IAB<any, any>>(A, B) {}
//  so we loose type checking...

// intentional type error
class testClass extends AB<boolean, string> {
  public a: number; // before 2.6.0 => type of 'a' properly detected as wrong, boolean expected
}

Expected behavior:
Like before typescript 2.6.0, extending a class with a mixin which takes generic types should be allowed.
Using mixin is a really common usage in js/ts to build classes which implement/inherit properties from more than one classe (sometimes named 'factories'). Before 2.6.0, typescript properly detected the union of class having generic types, but currently this generates TS2562 errors, so its no more possible to construct typed generic mixins.

In a more generic way:

function A<T>() {
  return class {};
}

// should be allowed
class B<T> extends A<T>() {}

Actual behavior:
TS2562, Base class expression cannot reference class type parameters (on T and U)

Playground Link: here

Related Issues: Partially related https://github.com/Microsoft/TypeScript/issues/19668

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.

Research direction

Start by reproducing TS2562 with the provided code sample or Playground Link using the affected TypeScript versions. Investigate the checker behavior for generic class type parameters referenced by mixin base class expressions, then add coverage showing the generic mixin is accepted and the intentional property type error remains detected.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.