Skip to content

Type inference issue in subclasses #15191

Description

TypeScript Version: 2.2.2

Code

class A<T> {
  foo: T;
}

class B extends A<'bar'> {
  foo = 'bar';
}

workaround:

class A<T> {
  foo: T;
}

class B extends A<'bar'> {
  foo = 'bar' as 'bar';
}

Expected behavior:
No Error;
Actual behavior:
Type string is not assignable to type 'bar';

I don't know if this behavior is intended.
I think type inference should be more accurate in this case to make programmers not to write as sometype once again.

Activity

  1. aluanhaddad commented on Apr 14, 2017

    @aluanhaddad
    Contributor

    The problem is that foo "overrides" (not really but in OO speak) the base property and is allowed to declare a less specific type.

    Improved workaround:

    class A<T> {
      foo: T;
    }
    
    class B extends A<'bar'> {
      readonly foo = 'bar';
    }

    Note there have been dozens of issues about inheriting exact signatures, and Nathan Shively-Sanders (@sandersn) worked very hard on multiple potential implementations. See #6118 and #10570 where this is discussed in detail.

    Personally, the compile time checked immutability in the above workaround is a nice side-effect at least.

  2. locked and limited conversation to collaborators on Jun 21, 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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions