Skip to content

Allow omitting name in template literal strings #40996

@JoshuaKGoldberg

Description

@JoshuaKGoldberg

Search Terms

ignore infer template literal omit name template literal infer

Suggestion

Can we omit the inferred names in string template literal types if we don't need their values?

Use Cases

Suppose you want to use a template literal type to find strings matching a template, but don't care what's in those inferred strings. You could use a name like ${infer _}, but that's a little extra verbosity.

type OnlyKeysContainingSmoosh<T> = keyof {
    [Key in keyof T as Key extends `${infer _}Smoosh${infer _}` ? Key : never]: T[Key];
};

// "Smoosh" | "PreSmoosh" | "SmooshPost"
type FilteredKeys = OnlyKeysContainingSmoosh<{
    Smoosh: 1,
    PreSmoosh: 2,
    SmooshPost: 3,
    NoKeyForYou: 4,
}>;

Examples

The proposal here would allow omitting the _ and _ in the above example:

type OnlyKeysContainingSmoosh<T> = keyof {
    [Key in keyof T as Key extends `${infer}Smoosh${infer}` ? Key : never]: T[Key];
}

(Separately, I also find it spooky that it's ok to have the same name for the two inferred types, but that might just be a separate issue...)

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions