Skip to content

Narrow type constraints - #7422

Closed
Nathan Shively-Sanders (sandersn) wants to merge 2 commits into
masterfrom
narrow-type-constraints
Closed

Narrow type constraints#7422
Nathan Shively-Sanders (sandersn) wants to merge 2 commits into
masterfrom
narrow-type-constraints

Conversation

@sandersn

Copy link
Copy Markdown
Member

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
Copy Markdown
Member Author

As discussed with Yui (@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
Copy Markdown
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
Copy Markdown
Contributor

This is already covered by #8010, closing.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

4 participants