TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Type variable constrained to primitive or union type not assignable to it

Open jeffreymorlan opened this issue 11 years ago • 1 comments

You can constrain a type variable to a primitive type like number (useful for a function intended to work on multiple different enum types), but you get an error upon trying to assign it to that type:

function binarySearch<T extends number>(arr: T[], elem: T) { /* ... */ }

function removeSorted<T extends number>(arr: T[], elem: T) {
    var idx = binarySearch(arr, elem); // Error - T not assignable to number
}

The same problem also exists for union types, even if the union is made up entirely of object types and not primitives.

jeffreymorlan avatar Feb 05 '15 03:02 jeffreymorlan

This is behaving according to spec, but the spec should probably change. @ahejlsberg ?

The problem is that there's no rule in 3.10.4 that actually makes T in T extends number assignable to the other T extends number. The rules for resolving a generic type parameter to its constraint type all go through apparent type and thus the source T "looks like" an object type, which isn't assignable to the primitive number constraint.

I think we need a bullet in 3.10.4 that says something like

  • T is primitive type and S is a type parameter constrained to a primitive type that is a subtype of T

RyanCavanaugh avatar Feb 05 '15 05:02 RyanCavanaugh