0

I recently stumbled upon the following snippet:

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

This is later used like below:

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

Can anybody help me figure out what [_ in 0 as Name] means?

I also found this bit in the playground but still...

stratis
  • 7,750
  • 13
  • 53
  • 94
  • 1
    to me the `in 0 as` is useless, `{[_ in Name]: T}` achieves the same here. But am I missing something ? – Matthieu Riegler Feb 17 '22 at 14:05
  • Here's the relevant section in the [mapped types documentation](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as) for key remapping with `as`. Is there some specific question that the documentation doesn't already answer? – Emma Feb 17 '22 at 14:06
  • @MatthieuRiegler What `{[_ in Name]: T}` does even mean? Why can't we just do `{[Name]: T}`? Also, `in 0` should have spit out zero iterations, right? – stratis Feb 17 '22 at 14:25
  • I also noticed that rewriting this as `type NamedProperty = { [Name: string]: T }` doesn't work the same way. – stratis Feb 17 '22 at 14:50

1 Answers1

3

{ [_ in 0 as Name]: T } means the same thing as { [_ in Name]: T } as the key remapping changes nothing here.

In mapped type, the left part defines the keys, very ofter we see it as [k in MyType] or [key in MyType]. Since the key won't be reused, its replace by an underscore (like it's ofter the case in JS/TS with unused function parameters).

So [_ in Name] means every key in the type name. Since Name is just a string, the mapped type will have only one key, the string.

{ [_ in 0 as 'myKey']: number }  ===  { myKey: number }

In the example you give { [Name: string]: T }, Name is not a type but a "variable". As you can see in the playground, the generic parameter is unused. In mapped types, [Name: string] every key that is of type string.


About the key remapping,

Per the documentation, the key remapping can be used to infer the keys from template literal types.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134