1

In TypeScript I know it's possible to interface a dictionary in the following way:

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

However, the external package I'm using returns a dictionary with a method on it to format the data contained in it for another purpose.

So I would like to interface it by doing something like the following:

interface MyDictionary {
  [key: string]: string;
  formatForSomethingElse(): any;
}

However this gives me the following error:

Property 'formatForSomethingElse' of type '() => any' is not assignable to string index type 'string'.ts(2411)

As the object I'm interfacing is external and I have no control over it. Is my only option in this instance, to change the dictionary value to type any?

JJ Pell
  • 846
  • 1
  • 8
  • 17
  • 2
    Does this answer your question? [Extend interface to contain a date type](https://stackoverflow.com/questions/63071377/extend-interface-to-contain-a-date-type) – ethane Aug 11 '20 at 15:31
  • That makes sense, unfortunately as the object is external I don't have the ability to change it – JJ Pell Aug 12 '20 at 07:16

2 Answers2

1

Maybe it is worth to rearrange your interface a bit to keep the items separately:

interface MyDictionary {
  items: { [key: string]: string; };
  formatForSomethingElse(): any;
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46
0

TLDR

I think you need to separate data and method with some depth

Answer

Terms of software oop Interface is some rules or blue print between A component and B component.

And class is data+method so it is good usecase to separate data and method

[key: string]: string | Function is not intuitive usecase with oop

Example

interface MyDictionary {
  [key: string]: string | Function;
  formatForSomethingElse(): void;
}

My recommendation is

interface MyDictionary {
  data : {
     [key: string]: string;
  }
  formatForSomethingElse(): any;
}
Stark Jeon
  • 1,107
  • 9
  • 24