Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference issue in subclasses #15191

Closed
tommytroylin opened this issue Apr 14, 2017 · 1 comment
Closed

Type inference issue in subclasses #15191

tommytroylin opened this issue Apr 14, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@tommytroylin
Copy link

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.

@aluanhaddad
Copy link
Contributor

aluanhaddad commented Apr 14, 2017

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 @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.

@sandersn sandersn added the Duplicate An existing issue was already created label Apr 14, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 21, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants