1

I have JSON objects with a large number of properties. I know some of the properties in advance, but the others are only known at runtime. All the objects have the same properties. What I would like to do is create an interface with the properties I do know, and access the others through an indexer.

For example, suppose I have the object {a: 1, b: '$', c: 12, d:53} and I only know a and b in advance. I would like to do something like:

interface Record {
    a: number;
    b: string;
    ... rest of fields: number ...
}

Using an indexer won't work, adding [name: string]: number to the interface causes an error, claimng that b is not a number.

Is there a way to do this?

zmbq
  • 38,013
  • 14
  • 101
  • 171
  • 2
    @Nicolas but they aren't strings, they are numbers. – VLAZ Nov 01 '20 at 13:50
  • 2
    You can use an intersection type. In your case `{[key: string]: number} & { a: number; b: string; }`. You can also use the [`Record` utility type](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype) `Record & { a: number; b: string; }` [Playground Link](https://www.typescriptlang.org/play?#code/C4TwDgpgBAsiAiBDYioF4oCUIGMD2ATgCYA8AzsAQJYB2A5gDRQ0CuAtgEYQEB8UAZFADeURAC5m7LgQDcUDhIrV6cgL4AodUVwAbRAWj4aFKADM8eCXCQoZm83gB0iR8DwAxKgA8IRABQATACUcgD0oXgA1lAAtFBUwADkZKKSnNzqDo4cjhT6wGQA6gkAFn4ARCUQOjp45SFQ4VGx8UkpqEq0dHZZOK54AAoGOFRkVHg0gQ1N0XEJyams6QRAA) – VLAZ Nov 01 '20 at 13:58

0 Answers0