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?

2
  • I think this should answer your question. Commented Sep 3, 2020 at 12:13
  • You can go let myData: Data & { [k: string]: any }; Commented Sep 3, 2020 at 12:35

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

7 Comments

let myData: Data & { [k: string]: any }; can keep the fields.
Indeed, but you should avoid any types at all costs
@hackape can I declare a new type like this?
yes using type extendedData = Data & { [k: string]: any };, however as I previously said: the any type should be avoided @AskarIbragimov
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.