0

I have a Typescript interface that is just a set of fields, e.g.

export interface Data {
   date_created: string;
   stamp: string;
 }
let myData: Data;

However, my case requires me to add "dynamic" fields that I can not hard-code before runtime, so I should be write something like

const dynamicFieldname = getDynamicFieldNameFromSomeDataSource(); // type is string. 
mydata[dynamicFieldname] = dynamicFieldvalue;

when I write this, I get a Typescript Error:

Error: TS7017: Element implicitly has an 'any' type because type 'Data' has no index signature.

How can I achieve the possibility to have these dynamic fields in my Typescript object, such as, how can I add the required 'index signature' to an interface?

onkami
  • 8,791
  • 17
  • 90
  • 176

1 Answers1

2

I think what you're looking for will look like this:

interface data {
    [key: string]: string;
}

NOTE: this won't allow you to keep the date_created and stamp fields, as those are also strings (basically if you use [key: string]: T, you can't use other hardcoded properties of type T anymore).

Zer0
  • 1,580
  • 10
  • 28
  • `let myData: Data & { [k: string]: any };` can keep the fields. – hackape Sep 03 '20 at 12:36
  • Indeed, but you should avoid any types at all costs – Zer0 Sep 03 '20 at 12:40
  • @hackape can I declare a new type like this? – onkami Sep 03 '20 at 13:42
  • yes using `type extendedData = Data & { [k: string]: any };`, however as I previously said: the any type should be avoided @AskarIbragimov – Zer0 Sep 03 '20 at 13:46
  • 1
    At all cost? That I’d disagree "at all cost". How could `dynamicValue` be typed then, if it’s indeed dynamic, like, from user input whatsoever. `any` is a type too, you just need to understand what you’re doing with that code. – hackape Sep 03 '20 at 13:59
  • @hackape well any symbolizes the compiler to just "stop checking". Sometimes there is no other option but if your API response got maybe three or four different responses it would be better to type it right away – Zer0 Sep 03 '20 at 14:28
  • Siding with hackape, any is needed if you don't know or have multiple different types. Such as passing different kinds of objects as the value. – KayKoder May 22 '23 at 17:31