'TypeScript template literal types

Last year Sam Stephenson (ex Basecamp/HEY) posted a very interesting tweet about some developments on the stimulus js library he was working on which unfortunately never the saw the light of day due to the recent basecamp fallout events.

Playing with TypeScript template literal types 🤯. Here’s an example showing how we could map a Stimulus controller’s static targets = [...] array to an interface with all of the generated properties:

I've been studying a bit of Typescript lately and was trying to decipher that specific tweet but it seems it's above my current level of understanding. I've already made an attempt in my previous post to understand the NamedProperty type here but I'm still very confused.

So, can anyone explain to me the following code?

type NamedProperty<Name extends string, T>
  = { [_ in 0 as Name]: T }

type UnionToIntersection<T>
  = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never
type ValueOf<T>
  = T[keyof T]

type TargetPropertyGroup<Name extends string>
  = NamedProperty<`has${Capitalize<Name>}Target`, boolean>
  & NamedProperty<`${Name}Target`, Element>
  & NamedProperty<`${Name}Targets`, Element[]>

// This type troubles me the most
type TargetProperties<Names extends string[]>
  = UnionToIntersection<ValueOf<{ [Name in Names[number]]: TargetPropertyGroup<Name> }>>

let controller!: TargetProperties<[ "form", "input", "result"]>

// Magical autocomplete happens here just after the dot!
let result = controller.

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source