Skip to content

Type argument inference doesn't seem to work correctly with generic type aliases #5417

Description

Hi, I found that the following example that uses type argument inference and generic type alias doesn't compile:

Example with generic type alias (does not work)

type Maybe<T> = T | void;

function get<T>(x: Maybe<T>): T {
    return null; // just an example
}

let foo: Maybe<string>;
get(foo).toUpperCase(); // I think T == string in this function call...

Error

test.ts(8,10): error TS2339: Property 'toUpperCase' does not exist on type 'string | void'.

Example with generic interface (works)

interface Maybe<T> {}

function get<T>(x: Maybe<T>): T {
    return null;
}

let foo: Maybe<string>;
get(foo).toUpperCase();

Version

1.8.0-dev.20151027

Activity

  1. mhegazy commented on Nov 13, 2015

    @mhegazy
    Contributor

    The problem is not type alaises. the issue here is that foo is of type string|void. here is a simpler example:

    function get<T>(x: T | void): T {
        return null; // just an example
    }
    
    let foo: string | void;
    get(foo).toUpperCase(); // T is still string|void
  2. seanchas116 commented on Nov 13, 2015

    @seanchas116
    ContributorAuthor

    Thanks! I now see the meaning of the error message.
    But isn't this a inconsistent behavior between generic type aliases and generic interfaces/classes?

  3. seanchas116 commented on Nov 13, 2015

    @seanchas116
    ContributorAuthor

    Actually, I tried this example first to achieve simple non-nullability:

    type Maybe<T> = T | void;
    
    function exists<T>(x: Maybe<T>): x is T {
        return x != null;
    }
    
    let foo: Maybe<string>;
    foo.toUpperCase(); // error
    if (exists(foo)) {
      foo.toUpperCase(); // OK
    }
  4. mhegazy commented on Nov 13, 2015

    @mhegazy
    Contributor

    clever :) a word of caution, trying to wrestle in non-nullable types in the system might be a tedious and brittle thing to do. For future references implementing non-nullable types is tracked by #185.

  5. ahejlsberg commented on Nov 24, 2015

    @ahejlsberg
    Member

    Now fixed by #5738.

  6. added
    BugA bug in TypeScript
    FixedA PR has been merged for this issue
    and removed
    QuestionAn issue which isn't directly actionable in code
    on Nov 24, 2015
  7. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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