Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Issue a warning when generic type inference produces {} #360

Copy link
Copy link
@RyanCavanaugh

Description

@RyanCavanaugh
Issue body actions

Motivating example (one of many):

function compare<T>(lhs: T, rhs: T): boolean {
  return lhs === rhs;
}

if(compare('1', 1)) { // Expected: Error -- I made 'compare' generic for a reason!
  /* ... */
}

Proposal

When generic type inference performs its Best Common Type operation (4.12.2), it should be an error if this returns {} when {} was not one of the input types.

This is entirely consistent with other behavior already in the compiler:

var foo = bar ? '1' : 1; // Error, no BCT between '1' and 1
function fn() { // Error, no BCT between '1' and 1
  if(foo) {
    return '1';
  } else {
    return 1;
  }
}

Open Questions

From @KamyarNazeri -- should this apply when there are zero input types? e.g.:

class List<T> {
    items: T[];
}

var x = new List(); // Probably want an error here

That seems desirable, but has some collateral damage:

function foo<T>(x: number, a?: T, b?: T) { }
foo(0); // Error, zero input types provided for inference

This would come up slightly more often than naively expected because many .d.ts authors (mistakenly) create generic types which don't actually consume their type parameters. Perhaps this warning would effectively discourage them from doing so?

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptAn idea for TypeScript

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.