Skip to content

Mapped types over subclassed arrays behave strangelyΒ #59260

Open
@Andarist

Description

@Andarist

πŸ”Ž 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

Metadata

Metadata

Assignees

Labels

Needs InvestigationThis issue needs a team member to investigate its status.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions