Typescript - How to type unknown properties of an object?

Viewed 4308

Suppose there is a variable resp receiving a response from the server:

const resp = await ServerResponse();

I know for sure that the response has a ready: boolean property:

console.log(resp);
/**
 * {
 *   "ready": true
 * }
 */

But there may be optional parameters, the type of which I do not know

console.log(resp);
/**
 * {
 *   "ready": true,
 *   "_startAt": 1234567890
 * }
 */

How should I type this?

interface R {
  ready: boolean;
  //...args: any; //something like this
}
const resp: R = await ServerResponse();

Or there is another way, without giving any to the resp variable, so that when accessing unknown properties, TS does not swear?

1 Answers

Well, we can make the value of the indexed property a loose type any

interface R{
  name: string;
  age: number;
  [prop: string]: any; // but this defeats the purpose of providing good typing.
}

Another approach would be to make additionalProperties a Dictionary

interface R {
  name: string;
  age: number;
  additionalProperties: { [prop: string]: string}; 
}

more you can check here as well Typescript interface for objects with some known and some unknown property names

Related