Unexpected behavior of generic constraints · Issue #3410 · microsoft/TypeScript (original) (raw)

The following code snippet compiles without type errors though the type variable T is constrained to string type.

function foo1(f: (s: string) => string) { return f("hello world"); }

function foo2(f: (s: number) => number) { return f(123); }

function genericBar(arg: T): T { return arg; }

var x1 = foo1(genericBar); var x2 = foo2(genericBar);

Non generic version nonGenericBar works as expected.

function nonGenericBar(arg: string) { return arg; }

var y1 = foo1(nonGenericBar); var y2 = foo2(nonGenericBar); // Type error

Of course, genericBar function is useless because constraining a type variable to a primitive type can be replaced by a non generic function like nonGenericBar. However, the behaviour is somewhat unexpected and inconsistent.