3
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 2

2

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
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to add | but I couldn't use it. I will add to my question about it.
@zynkn That is a different error. You can not call .map() on a number. You have to type check your data[key] e.g. with hasOwnProperty("map")
yeah, I know I can't call map() on the type number I am not trying to do this. I think I need to edit my code little bit.
0

You can use Type Intersection as followed:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.