Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS interface static name and [key: string]

Tags:

typescript

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)

like image 822
kyun Avatar asked Dec 19 '25 21:12

kyun


1 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
  }
}
like image 75
Murat Karagöz Avatar answered Dec 21 '25 18:12

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!