microsoft / microsoft/TypeScript

Mapped types over subclassed arrays behave strangely

Open
#59,260 1 comment 1 reaction 1 assignee View on GitHub

@ahejlsberg is already working on this.

Since Jul 26, 2024.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

mapped type array subclass numeric constraint

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.0-dev.20240712#code/MYGwhgzhAEDKCuAjAggJ1WAngHgCoD5oBTADwBciA7AExjQxwOgG8BYAKGmnAjIAV4EABZFqALmjwaRAGYBLSqOgAfaLgDcHAL4cOZTAAciaorzzFyVWtABKRMNQD2lEJnpZsYSpnyEAvCwcXADaANLQCtAA1kSYjjJqALoSuGGJmuxaGXqGxnYQ8CBk0AG4pmTYCCjoHpTwALaIRKi+GQD0bVzQAHoA-DlG0ALCJbamhWTBAEQGgkJT6RwdXX1AA

💻 Code
class SubArray<T> extends Array<T> {
  lastPushed: undefined | T;
}

type Test<T extends ReadonlyArray<any>> = {
  [K in keyof T]: T[K];
};

type Result = Test<SubArray<number>>;
//   ^?
type Push = Result["push"];
//   ^?
🙁 Actual behavior

This mapped type doesn't have a homomorphic instantiation - its arrayness is not preserved. But yet all members are mapped to the Array's type argument

🙂 Expected behavior

I'm not entirely sure. On one hand, it feels that those members should be instantiated with the type of the original member. This wouldn't work with generic mapped types as T[K] has the numeric constraint when T has an array/tuple constraint. So the generic constraints wouldn't match what those could end up being instantiated with.

Should the result be a remapped subclassed array? That means that extra members wouldn't be mappable... but hey, regular array methods etc arent. So perhaps that's the most appropriate solution here.

cc @ahejlsberg

Additional information about the issue

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.