Skip to content

Restricted generic ArrayLike parameter is deduced as never[] for empty array argument #11082

Closed
@zenmumbler

Description

@zenmumbler

TypeScript Version: 2.0.3

Code

interface MutableArrayLike<T> {
    readonly length: number;
    [n: number]: T;
}

type ArrayOfNumber = MutableArrayLike<number>;
type ArrayOfConstNumber = ArrayLike<number>; // has readonly subindex

interface vec3 {
    // the `out` array is modified and then returned as the function result
    subtract<T extends ArrayOfNumber>(out: T, a: ArrayOfConstNumber, b: ArrayOfConstNumber): T;
}

// later..
const result = vec3.subtract([], vA, vB);

Expected behavior:
Param out and the result are of type number[] or some looser type.

Actual behavior:
Param out and the result are of type never[]

Comments
strictNullChecks is on.

I realise that the compiler gets no help from an empty array parameter to deduce the type of its contents, but I was hoping my restricting of type T would either make it force the the type or throw an error. Making it a never[] seems a bit useless though I can intuit some of the reasoning of the compiler.

The interface works like this as the vec3 interface (from gl-matrix) deals with simple arrays or typed arrays so I typed everything to at least force numbers in there, but I was hoping that I could get it to set the result type to the type of the argument that I pass into the out param, because that is the value that is returned to facilitate easier chaining.

This may be a design limitation but I can always hope.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions