1

as title says, have an interface that includes a fixed property and optional property, both of type string.

export interface Test{
    [index: string]: {
        'list': string[];    // <<< throws TS2411 error
        [index: string]: number;
    }
}

This throws TS error TS2411: Property 'list' of type 'string[]' is not assignable to string index type 'number'.

How can I work around that ?

I know that list element will exist within each root index object, all other properties (if they exist) are of type number.

if I change the interface to:

export interface Test{
    [index: string]: {
        'list': string[];    
        [index: string]?: number;  // <<< throws TS7008 error
    }
}

then I get TS7008: Member 'number' implicitly has an 'any' type.

pete19
  • 333
  • 1
  • 3
  • 17
  • Please share the data, what you are trying to assign – Sifat Haque May 01 '21 at 22:59
  • @SifatHaque data is not needed as I don't wanna restructure it, look at the OP and the problem. TS does not seem to allow to define a KNOWN property alongside optional properties of (unknown property name) of same type... – pete19 May 02 '21 at 06:52
  • Yeah, there really isn't any perfect solution for this in TS. See the answer to the other question for various options. A translation of the code there to here looks like [this](https://tsplay.dev/Nr2ZoN) – jcalz May 02 '21 at 13:56

1 Answers1

1

It is because you're setting the [index: string]: number; part - that allows you to set any string to a number, which also covers the string of "list", so there's a clash. If you need a "list" value as well as an unknown number of other values, I'd suggest something like:

export interface Test {
  [index: string]: {
    list: string[];
    items: {
      [index: string]: number;
    }
  }
}
Dean James
  • 2,491
  • 4
  • 21
  • 29
  • right, I know that and the error states that. Your solution would restructure my data, which is not what I want. So back to the OP, I cannot define a KNOWN property in a TS and optional properties of (unknown property name) of same type ? – pete19 May 02 '21 at 06:51
  • 1
    No. The issue is your data structure pushes against the predictability that static type checking is meant to provide. Edit: Sorry I just reread your comment. If you have them of the same type, that should be fine. – Dean James May 02 '21 at 08:55