Skip to content

Polymorphic 'this' with Generics #7818

@shlomiassaf

Description

@shlomiassaf

TypeScript Version:
[email protected]
[email protected]

Code

// 2 Simple interfaces, child extends parent.
interface ParentData {
    parentData: string;
}
interface ChildData extends ParentData {
    childData: string;
}


// 2 Simple classes with Generics.
// Each class has a "placeholder" method.
// Type parameter must satisfy the XData interface above.
class Parent<T extends ParentData> {
    toBeMethod: (value: string) => this;
}


// Here we have 2 "extends"
// 1) Type parameter T extends ChildData interface (which extends ParentData)
// 2) Child<T> extends Parent<T>, Parent will have a type parameter T that is ChildData (at least)
class Child<T extends ChildData> extends Parent<T> {
    yetAnotherToBeMethod: (value: string) => this;
}

// NOTE: The "placeholder" methods have a return signature of 'this', this + generics cause's the issue.

// These are factories for creating instances of Parent,Child
// 2 type parameters, T (with constraint) and Z also with constraint related to T.
export class ParentFactory<T extends ParentData, Z extends Parent<T>> {}
export class ChildFactory<T extends ChildData, Z extends Child<T>> extends ParentFactory<T, Z> {}

Expected behavior:
No errors...

Actual behavior:

error TS2344: Type 'Z' does not satisfy the constraint 'Parent<T>'.
  Type 'Child<T>' is not assignable to type 'Parent<T>'.
    Types of property 'toBeMethod' are incompatible.
      Type '(value: string) => Child<T>' is not assignable to type '(value: string) => Z'.
        Type 'Child<T>' is not assignable to type 'Z'.

Type 'Child' is not assignable to type 'Z'.

How Child is not assignable to type 'Z' if:
export class ChildFactory<T extends ChildData, Z extends Child> extends ParentFactory<T, Z> {}

Metadata

Metadata

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions