Skip to content

Infer and preserve the label of an element for Named Tuples  #49122

Closed

Description

Suggestion

Allow Typescript compiler to Infer and preserve the label of an element for Named Tuple types

🔍 Search Terms

label, named tuples, variadic

✅ 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.

⭐ Suggestions

While inferring the type from the named tuple, we should be able to preserve the label of the tuple at that position.
Currently we are only able to infer the type and the label associated with it is not preserved

📃 Motivating Example

Here it would make sense to be able to infer the label foo
so that InferFirst returns [foo: number]

type InferFirst<T extends any[]> = 
  T extends [infer H, ...infer _]
  ? [H]
  :never

type Ex1 = InferFirst<[foo: number, bar: string, baz: boolean]>
//   ^?  type Ex1 = [number]

💻 Use Cases

Currently, there is a workaround ,where we distinctly need to infer R the Rest of the elements and then split the tuple into two types and infer H with the label preserved

// This preserves the label
type InferFirstAndPreserveLabel<T extends any[]> =
  | T extends [any, ...infer R]
    ? T extends [...infer H, ...R]
      ? H
      : never
    : never  


type Ex2 = InferFirstAndPreserveLabel<[foo: number, bar: string, baz: boolean]>
//   ^?    type Ex2 = [foo: number]

Activity

  1. ajitjha393 commented on May 16, 2022

    @ajitjha393
    Author

    Mateusz Burzy��ski (@Andarist) what are your views on this

  2. Andarist commented on May 16, 2022

    @Andarist
    Contributor

    I think that it would be really cool if this could "just work" because from the user's PoV this is a little bit surprising.

    I took a quick look at the implementation and I think that adding support for this goes beyond my current understanding of the codebase. Maybe I could take a stab at this if I could get some pointers from people more intimate with the inner workings of TS.

    Essentially the inference candidate for H is first computed here:
    https://github.dev/microsoft/TypeScript/blob/0414deeaaf211ee000548c30fd81aa09b311abb7/src/compiler/checker.ts#L22358
    and later on retrieved from the candidates within this call:
    https://github.dev/microsoft/TypeScript/blob/0414deeaaf211ee000548c30fd81aa09b311abb7/src/compiler/checker.ts#L22979

    The problem is that the candidate is assigned without any label because the target site isn't a tuple or anything. And later on it's retrieved using a mapper from type arguments and stuff.

    Whereas in the working version the source type (a tuple type) is being sliced to create the inference candidate~:
    https://github.dev/microsoft/TypeScript/blob/0414deeaaf211ee000548c30fd81aa09b311abb7/src/compiler/checker.ts#L22789

    So in this case there is no problem in preserving the labels as they are sliced within sliceTupleType too.

    I was thinking about creating a weak map in the inference context that would map a candidate to the label and then to get that label at the final target if the target's parent is a tuple type. However, this wouldn't quite work with inferred primitives. So perhaps creating an array for position-based labels would work instead. But then... getTypeFromInference just gets a type for H and it's pretty much decoupled from the contextual information that the target parent type is a tuple and I have no idea how to juggle this information around in a clean way.

    The last time the target type is being observed as tuple is here:
    https://github.dev/microsoft/TypeScript/blob/0414deeaaf211ee000548c30fd81aa09b311abb7/src/compiler/checker.ts#L17165

    So perhaps this could be accomplished here, somehow, if the mapper would be more specialized. But I didn't yet wrap my head around those mappers to even attempt experimenting with this.

  3. added
    Suggestion
    Experience Enhancement
    on May 16, 2022
  4. RyanCavanaugh commented on May 16, 2022

    @RyanCavanaugh
    Member

    As discovered above 😅, it's often difficult to traffic these labels around in an elegant way.

    We'd be open to a PR that fixes this cleanly, but I'm not sure that's possible today.

  5. DanielRosenwasser commented on Mar 21, 2024

    @DanielRosenwasser
    Member

    Duplicate of #43020, but also this now works as of TypeScript 5.2, probably thanks to Josh Ghoulberg 👻 (@JoshuaKGoldberg)'s #53356.

  6. DarrenDanielDay commented on Apr 6, 2025

    @DarrenDanielDay

    The code in issue still has the same behavior in TypeScript 5.8.2.

    type InferFirst<T extends any[]> = 
      T extends [infer H, ...infer _]
      ? [H]
      :never
    
    type Ex1 = InferFirst<[foo: number, bar: string, baz: boolean]>
    //   ^? expected type: Ex1 = [foo: number]
    //   ^? actual type: Ex1 = [number]

    I'm wondering if we can change the H into a tuple to keep the names. But unfortunately it still does not work as expected in TypeScript 5.8.2.

    type InferFirst1<T extends any[]> = 
      T extends [...infer H, ...infer _]
      ? H
      :never
    
    type Ex1 = InferFirst2<[foo: number, bar: string, baz: boolean]>
    //   ^ expected type: Ex1 = [foo: number]
    //   ^ actual type: Ex1 = [any]
    
    // With length constraint:
    type Tuple1 = [any];
    type InferFirst2<T extends any[]> = 
      T extends [...infer H extends Tuple1, ...infer _]
      ? H
      :never
    
    type Ex2 = InferFirst2<[foo: number, bar: string, baz: boolean]>
    //   ^ expected type: Ex2 = [foo: number]
    //   ^ actual type: Ex2 = [any]

    Playground Link

    This implementation is inspired by the template literal types: each infer of template literal types in a continuous group but not the last one in group has to match at least one character.

    type TemplateMatch1 = "abcde" extends `${infer A}${infer B}cd${infer E}` ? [A, B, E] :never
    //   ^ type: TemplateMatch1 = ["a", "b", "e"]
    type TemplateMatch2 = "abcde" extends `${infer A}${infer B}${infer Empty}cd${infer E}` ? [A, B, Empty, E] :never
    //   ^ type: TemplateMatch2 = ["a", "b", "", "e"]
    type TemplateMatch3 = "abcde" extends `${infer A}${infer B}${infer Empty}${infer CannotMatch}cd${infer E}` ? [A, B, Empty, CannotMatch, E] :never
    //   ^ type: TemplateMatch3 = never
    // Template matching works as expected.

    Playground Link

    So what if we match the tuple with given length?

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

    Experience EnhancementSuggestion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions