Issue
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.
Solution
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
})
Answered By - bogdanoff
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.