Home > Software engineering >  Typescript peculiarities in mapped types
Typescript peculiarities in mapped types

Time:02-18

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

CodePudding user response:

{ [_ 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.

  • Related