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

Narrow type constraints #7422

Closed
wants to merge 2 commits into from
Closed

Narrow type constraints #7422

wants to merge 2 commits into from

Conversation

sandersn
Copy link
Member

@sandersn sandersn commented Mar 7, 2016

Fixes #6445

If the narrowed type is assignable to the type parameter's constraint, then narrow to a type parameter with the constraint of the narrowed type. In the example in the bug,

isDerived(x) && isDerived(y) && x.d == y.d;

After narrowing, x and y have the type T extends Derived instead of T extends Base.

If the narrowed type is assignable to the type parameter's *constraint*,
then narrow to a type parameter with the constraint of the narrowed type.
@sandersn
Copy link
Member Author

sandersn commented Mar 8, 2016

As discussed with @yuit, the reason I narrow to T extends Derived instead of Derived is that I wanted to enable to returning the narrowed type. But this still doesn't work. Observe f and f2:

function f<T extends Base>(x: T) {
  return isDerived(x) && x; // f's return type appears to be `T extends Base`
}
function f2<T extends Base>(x: T): T {
  return isDerived(x) && x;
  // error: 'T' is not assignable 'T'; 'Derived' is not assignable to 'T'
}

This should work by analogy with the non-generic version:

function g(x: Base) { 
  return isDerived(x) && x; // g's return type is Derived
}

@DanielRosenwasser
Copy link
Member

It seems like if one of your return type candidates is a type parameter, you don't want to return the narrowed type there. You just want to return the type parameter itself. I can't specifically think of other types that might have this characteristic.

@mhegazy
Copy link
Contributor

mhegazy commented Apr 21, 2016

This is already covered by #8010, closing.

@mhegazy mhegazy closed this Apr 21, 2016
@mhegazy mhegazy deleted the narrow-type-constraints branch November 2, 2017 21:02
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

Successfully merging this pull request may close these issues.

4 participants