Express unknown string object key in TypeScript

I'm creating a TypScript Declaration file for a client library with a method that returns an object having a variable string key (a record id):

getRecords(...): {
  [string]: {  // ??
    first: string,
    last: string,
    ...
  }
};

What is the correct way to specify that the key value is only known at runtime, and what is the reference for this?

getRecords returns something like:

{
  'GuT9b...pX': {
    first: 'John',
    last: 'Doe',
    ...
  },
  'aMe4T...lk': {
    first: 'Jane',
    last: 'Doe',
    ....
  }
}

(Note that this is a wrapper for an HTTP API written in PHP so I have no control over the result being an associative array (i.e. JavaScript hash), instead of an array with an .id field in each element.)

1 answer

  • answered 2017-06-17 20:03 artem

    It's called indexable type:

    function getRecords(key: string): { [s: string]: { first: string /*, ...*/ } } {
        return { [key]: { first: 'John' } }
    }