Typescript: Unnecessary widening of function argument's type

Created on 2 Nov 2017  路  5Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.6.1 (2.7.0-dev.20171102)

Code

type Nominal<Kind extends string, Type> = Type & {
    [Symbol.species]: Kind;
};

type A = Nominal<'A', string>;

declare const a: Set<A>;
declare const b: Set<A>;

const c1 = Array.from(a).concat(Array.from(b)); // Argument of type 'string[]' is not assignable to parameter of type 'Nominal<"A", string> | ReadonlyArray<Nominal<"A", string>>'.
const c2 = Array.from(a).concat(Array.from<A>(b)); // OK

const aa = Array.from(a);
const bb = Array.from(b);
const cc = aa.concat(bb); // OK

Expected behavior:
No errors.

Actual behavior:
With Array.from(a).concat(Array.from(b)) we have an error Argument of type 'string[]' is not assignable to parameter of type 'Nominal<"A", string> | ReadonlyArray<Nominal<"A", string>>'.

In 2.5.3 it works fine.

Bug Fixed

Most helpful comment

This one is actually caused by a subtle issue introduced by #18363. I have a fix that I will put up shortly. Meanwhile, the change to lib.d.ts is probably fine, but strictly speaking isn't needed.

All 5 comments

A smaller repro:

type A = string & { n: number };
declare function from<T, U = T>(iterable: Iterable<T>, mapfn?: (v: T, k: number) => U): U[];
declare function concat<T>(a: ReadonlyArray<T>, b: ReadonlyArray<T>): T[];

declare const iterA: Iterable<A>;
const a: A[] = from(iterA); // OK
const cat: A[] = concat(a, from(iterA)); // Error

It would work if you remove U and mapfn from from, but that shouldn't be necessary.
We've had some similar problems with Array and ReadonlyArray in the past.

We need to split the from function into two overloads i would say.

@mhegazy Should that really be necessary? We usually recommend to unify signatures like that.

Should that really be necessary? We usually recommend to unify signatures like that.

The U here is just like map, you want to allow a function to transform the input to a different type and infer that independently.

This one is actually caused by a subtle issue introduced by #18363. I have a fix that I will put up shortly. Meanwhile, the change to lib.d.ts is probably fine, but strictly speaking isn't needed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  路  3Comments

blendsdk picture blendsdk  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments