Skip to content

Typescript fails to throw error when a generic is assigned to another generic of whom it's generic type is a superset #13970

Closed
@scamden

Description

@scamden

TypeScript Version: 2.1.4

Code

// A *self-contained* demonstration of the problem follows...
export interface MyInterface {
  myFunction(): Promise<number | string>;
}

export class MyClass implements MyInterface {
  async myFunction() { // inferred return type Promise<number | string | string[]>
    let num = 1;
    let text = 'text';
    if (num) {
      return num;
    }
    if (text) {
      return text;
    }
    return [text];
  }
}

Expected behavior:
TS throws an error that MyClass incorrectly implements MyInterface
type Promise<number | string | string[]> not assignable to Promise<number | string>

otherwise a client using the class as MyInterface can call the method and only handle a return promise of string or number and have errors when the promise is resolved with the array.

Actual behavior:
No error is thrown. (It's worth noting this doesn't repro without the generic. If for example the method were not async.) This also is not thrown if the return type is manually specified as Promise<number | string | string[]> just to be clear inference is not to blame.

Metadata

Metadata

Assignees

No one assigned

    Labels

    CanonicalThis issue contains a lengthy and complete description of a particular problem, solution, or design

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions