1

I am trying to type objects that would look like :

{
    name: "toto",
    index: [ 1, 2, 3],
    foo: [ "foo1", foo2", "foo3"],
    bar: [ "bar1", "bar2","bar3"]
}

I know for sure that I will have the name and index attributes, however I don't know whether I will have one or x "foo" attributes.

I tried the following interface:

export interface MyInterface {
    name: string;
    index: Array<number>;
    [seriesname: string]: Array<string>;
}

The error is thrown for the row:

name: string;

Property 'name' of type 'string' is not assignable to string index type 'string[]'.ts(2411)

I seems to me that all my attributes MUST be compatible with the dictionary I described with the row:

[seriesname: string]: Array<string>;

Which means I cannot type my object like this. Is there a way to do it ? (I don't want to modify the object, as I receive it from another application.)

PleaseHelp
  • 133
  • 9
  • 1
    Can you paste your whole code ? just by seeing the interface i cant tell what wrong you are doing – Sakshi Dec 11 '20 at 14:15
  • Do you know what possible "seriesname" there are, or is it completely free-form? – crashmstr Dec 11 '20 at 14:18
  • I don't know what seriesname there will be, but I know that their value will always be of type Array – PleaseHelp Dec 14 '20 at 08:01
  • I don't think it is relevant to paste my whole code, because the vscode Typescript linter reacts when I modify the interface – PleaseHelp Dec 14 '20 at 08:03
  • this question has been marked as duplicate, I used the information in the other post to solve my problem, thanks everyone – PleaseHelp Dec 14 '20 at 13:44

1 Answers1

0

If you know that all your arrays will of type either number or string, your interface could serve both and add the types to the name property:

export interface MyInterface {
    name: string | Array<number> | Array<string>;
    index: string | Array<number> | Array<string>;
    [seriesname: string]: string | Array<string> | Array<number>;
}

The solution above is detailed explanation here: typescript-book

This could get quite messy, depending on different types and properties though.

Kiwi
  • 38
  • 5
  • 1
    this seems to work, but don't we lose the point of typing here ? I would have to take into account the fact that my seriesname attributes could be strings (rather than arrays) everywhere in my code. – PleaseHelp Dec 14 '20 at 08:34
  • for example, I would get the following error : "Property 'forEach' does not exist on type 'string | string[] | number[]'." – PleaseHelp Dec 14 '20 at 08:34
  • @PleaseHelp this is true, this just shifts the problem further down the line, as you could then use `instanceof` or `typeof` depending on your style – Kiwi Dec 17 '20 at 23:40