Skip to content

Type error with 'extends' constraint and inheritance #17316

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

Closed
remagpie opened this issue Jul 20, 2017 · 2 comments
Closed

Type error with 'extends' constraint and inheritance #17316

remagpie opened this issue Jul 20, 2017 · 2 comments

Comments

@remagpie
Copy link

remagpie commented Jul 20, 2017

TypeScript Version: 2.4.1

Code

interface A {
  a: number;
}

interface B extends A {
  b: number;
}

function x(b: B): void {}
const y: <C extends A>(c: C) => void = x;

Expected behavior:
No Type Error

Actual behavior:
Type error with message :

Type '(b: B) => void' is not assignable to type '<C extends A>(c: C) => void'.
  Types of parameters 'b' and 'c' are incompatible.
    Type 'C' is not assignable to type 'B'.
      Type 'A' is not assignable to type 'B'.
        Property 'b' is missing in type 'A'.

Comment
Weirdly, it doesn't show any errors on Playground, but it shows errors when compiled on local project.

@remagpie remagpie changed the title Type error with 'extends' constraint and Type error with 'extends' constraint and inheritance Jul 20, 2017
@jcalz
Copy link
Contributor

jcalz commented Jul 20, 2017

This is intended behavior.

Playground is currently using TypeScript 2.3.3. Stricter checking for generic functions was introduced in TypeScript 2.4.

The error message is a good one. If I change your implementation of x() to actually use the b parameter:

function x(b: B): void { 
  console.log(b.b.toString()); // expects b.b to be defined
} 
const y: <C extends A>(c: C) => void = x;  

Then you can see why assigning x to y is flagged. You can apparently call y() on any A, but this will blow up at runtime unless the parameter is a B:

y({'a': 2});  // no error in TS, but TypeError at runtime

EDIT: of course, your next question might be: given that argument, why doesn't the following throw a type error?

const y: (a: A) => void = x;  // just fine apparently

The answer is: 🤷. Parameter bivariance is unsound and makes me sad, but I guess it allows for some useful programming patterns. See #14973 for some discussion and pointers to docs.

@remagpie
Copy link
Author

@jcalz
I'm still confused about your EDIT part, but I think my problem is answered.
Thank you for your help.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants