Echo
Echo

Reputation: 631

How to index interfaces with an array of strings in typescript

I have an object with type Test below. I am only interested in certain keys of that object, so I created an array of strings. I then looped through these keys of interest and attempt to access the obj using the bracket notation.

interface Test {
  field1: {
    subfield1: string;
    subfield2: string;
    ...
  };
  field2: string;
  field3: number;
  ....
}

const obj: Test = {
  field1: {
    subfield1: 'hello',
    subfield2: 'world',
    ...
  },
  ...
}

const keysOfInterest = ['field1', 'field3', ...]

keysOfInterest.forEach((key) => {
  if (obj[key] === 'Some condition') {
    // Perform some logic
  }
})

But typescript is giving me an error No index signature with a parameter of type 'string' was found on type 'Test'.. I'd still like to get the intellisense provided.

Thank you.

Upvotes: 0

Views: 668

Answers (1)

bogdanoff
bogdanoff

Reputation: 2358

It will work only when you set type of keysOfInterest to (keyof Test)[].

interface Test {
  field1: {
    subfield1: string;
    subfield2: string;
  };
  field2: string;
  field3: number;
}


const obj: Test = {
  field1: {
    subfield1: 'hello',
    subfield2: 'world',
  },
  field2: 'f2',
  field3:  3
}

const keysOfInterest: (keyof Test)[]  =  ["field1", "field2"]


keysOfInterest.forEach((key) => {
    const v = obj[key] // no errors
})

Playground Link

Upvotes: 2

Related Questions