0

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.

1
  • the "Omit" utility type could help you : typescriptlang.org/docs/handbook/… You could define your "obj" without some keys from Test type you are not interested in Commented Oct 26, 2022 at 10:17

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

You're answer helped. Modified it further by using the Pick type. Thank you!

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.