Skip to content

Mapped Type [Lhs of Rhs] Syntax for Array and Tuple TypesΒ #54575

Open

Description

Suggestion

πŸ” Search Terms

mapped type, of, array, tuple

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

A new [Lhs of Rhs] syntax in mapped type to map over values of array and tuple types:

type ResultType = {
    [V of SourceType]: DoSomethingWith<V>
}

Rhs does not need to be a type parameter.
Rhs must extend readonly unknown[] or a type error is raised.

πŸ“ƒ Motivating Example

type Foo = ['hello', 'world']

type Bar = {
    [V of Foo]: V[]
}
// Bar = ['hello'[], 'world'[]]

πŸ’» Use Cases

Currently, to do the same as in motivating example, one might intuitively write:

type Bar = {
    [K in keyof Foo]: Foo[K][]
}

However this is incorrect and is a mistake that's potentially difficult to spot.

Instead one must either introduce a generic intermediate type:

type Transform<T> = {
    [K in keyof T]: T[K][]
}

type Bar = Transform<Foo>

Or use the infer workaround:

type Bar = Foo extends infer T ? {
    [K in keyof T]: T[K][]
} : never

Both workarounds are not immediately obvious to inexperienced developers, less ergonomic, and will silently break when Foo is no longer an array or tuple type without putting extra constraints.

Activity

  1. jcalz commented on Jun 8, 2023

    @jcalz
    Contributor

    Presumably if #27995 were fixed we wouldn't need such a feature? Is there a reason we'd want this feature instead of fixing #27995?

  2. NonSpicyBurrito commented on Jun 8, 2023

    @NonSpicyBurrito
    Author

    Presumably if #27995 were fixed we wouldn't need such a feature? Is there a reason we'd want this feature instead of fixing #27995?

    I would say both the fix and this feature can co-exist, as the second (ergonomics) and third (enforcing rhs must extend readonly unknown[]) points this feature provides are still valuable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions