0

I came across the below syntax in a typescript file that I didn't recognize and have not been able to find it in the docs. It looks like the groups parameter should be an object with a groupName property, but I don't understand the syntax used for the property name. Can someone enlighten me?

export declare type CustomPatternMatcherFunc = (
  /**
   * The full input string.
   */
  text: string,
  /**
   * The offset at which to attempt a match
   */
  offset: number,
  /**
   * Previously scanned Tokens
   */
  tokens: IToken[],
  /**
   * Token Groups
   */
  groups: {
    [groupName: string]: IToken[] // <-- here
  }
) => CustomPatternMatcherReturn | RegExpExecArray | null
phil-daniels
  • 574
  • 2
  • 10
  • 28
  • Does this answer your question? [ES6 Map in Typescript](https://stackoverflow.com/questions/30019542/es6-map-in-typescript) – Tobias S. Apr 17 '22 at 00:34

1 Answers1

0

Sure. Here you are: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

But let me quickly explain what it is about:

You can declare a "generic" key inside an object, lets say you want to provide an object where you don't know how the keys are called, for example in a map where you map (as I am working on Discord Bots lately) commands for a discord bot to static answers, then you know that the key should be a string, the name of the command, and the value should be a string too, the static answer for the command.

Now you don't actually know how the key is named when declaring the type, but you always know that the key is a string and the value is a string. To declare such a type you can use index signatures:

type T = {[commandName: string]: string}

the syntax might be somewhat confusing as you assign a "name" to the key type, but it comes in handy if you have more complex types like for example


const obj = {key1: "test", key2: "test2"}

type ObjT = typeof obj

type T = {[key in keyof ObjT]: ObjT[key]}

as it is this example is kinda pointless, but the "name" you have is quasi the type of the key you are "mapping", so it is once "key1" and then ObjT[key] is like ObjT["key1"] and that is the type of the value for key1, in this case "test1", and then the same for "key2". The type is esentially {key1: "test1", key2: "test2} - as I said, pointless.

Quick note: there is a quicker syntax that might be considered more clean for the first example I gave: Record<string,string>. It is essentially the same I did above, a object with string keys and string values.