Skip to content

Homomorphic mapped generic array type sometimes no longer seen as an arrayΒ #57744

Closed
@jcalz

Description

@jcalz

πŸ”Ž Search Terms

conditional, mapped, array

πŸ•— Version & Regression Information

⏯ Playground Link

Playground link

πŸ’» Code

type MustBeArray<T extends any[]> = T

type Hmm<T extends any[]> = T extends number[] ?
    MustBeArray<{ [I in keyof T]: 1 }> : // <-- error!
    //          ~~~~~~~~~~~~~~~~~~~~~
    // Type '{ [I in keyof T]: 1; }' does not satisfy the constraint 'any[]'.
    // Types of property 'toString' are incompatible.
    // Type 'number' is not assignable to type '() => string'.(2344)
    never;

type X = Hmm<[3, 4, 5]>
//   ^? type X = [1, 1, 1]

πŸ™ Actual behavior

{[I in keyof T]: 1} is not seen as an array type inside of Hmm<T>, causing a compiler error. Something about the conditional type re-constraining T to another array type causes it to fail.

πŸ™‚ Expected behavior

The code should compile without error.

Additional information about the issue

Comes from this Stack Overflow question.

I'm a bit concerned that I can't seem to work around this without //@ts-ignore, since the normal approaches of Extract<T, any[]> don't help (they end up just doing the same conditional type thing again which break things) and T & any[] kind of works but you end up with intersections of arrays which nobody likes.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueRecent RegressionThis is a new regression just found in the last major/minor version of TypeScript.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions