Typescript: Allow omitting name in template literal strings

Created on 8 Oct 2020  路  3Comments  路  Source: microsoft/TypeScript

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:

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

Most helpful comment

Just use a lockfile and you'll be good 馃檪

All 3 comments

I think you can now write string in those slots and it will work kind of like an existential type parameter (e.g. ? extends string). Is that what you want?

Oh geez. My TSConf 2020 talk is going to be a little outdated... thanks! 馃槄

Just use a lockfile and you'll be good 馃檪

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Roam-Cooper picture Roam-Cooper  路  3Comments

blendsdk picture blendsdk  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

siddjain picture siddjain  路  3Comments