Skip to content

Unexpected behavior of generic constraints #3410

Closed
@kseo

Description

@kseo

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<T extends string>(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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" insteadFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions