TS interface static name and [key: string]

Viewed 1212
interface P{
  data: {
    sub: number
    [key: string]: {
      arr: Array<number>
    }
  }
}

My data could be

data = { 
  sub: 1,
  DYNAMIC1: [1,2,3],
  DYNAMIC2: [3,4,5]
}

or

data = { 
  sub: 1,
  RANDOM1: [3],
  DYNAMIC1: [9,0,0]
}

My IDE throw this error message

Property 'sub' of type 'number' is not assignable to string index type '{ arr: number[]; }'.ts(2411)

How can I use the static attributes name and dynamic together

added

I already use | but still error from another code.

{
  data[key].map((num:number, index:number)=> ...) // key can not be `sub`. key always be the type `Array<number>`
}

above code throw this error message

Property 'map' does not exist on type 'number | number[]'. Property 'map' does not exist on type 'number'.ts(2339)

2 Answers

You are defining an index signature which enforces the return type for all properties to match the index signature return type. However you can fix it by using the union operator e.g.

interface P {
  data: {
    [key: string]: number | Array<number>;
  };
}

If you want to keep sub as defined property, you have to extend the index with the concrete type of number e.g.

interface P{
  data: {
    sub: number
    [key: string]: Array<number> | number
  }
}

You can use Type Intersection as followed:

type P = {
  data: {
    [key: string]: number | Array<number>;
  } & {
    sub: number
  };
}
Related