Answer the question
In order to leave comments, you need to log in
Why does a type error occur?
Hello,
Can you tell me why typescript throws an error in this situation:
type Test = {
srn: number
}
const test: Test = { srn: 123 };
['srn', 'qre'].forEach((p) => {
if (typeof test[p] === 'number') {
test[p] = 34;
}
})
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Test'.
No index signature with a parameter of type 'string' was found on type 'Test'.
Answer the question
In order to leave comments, you need to log in
Option 1:
type Test = {
srn: number;
qre?: unknown;
};
const test: Test = { srn: 123 };
(['srn', 'qre'] as const).forEach((p) => {
if (typeof test[p] === 'number') {
test[p] = 34;
}
});
type Test = {
srn: number
}
const test: Test = { srn: 123 };
['srn', 'qre'].forEach((p) => {
if (p === 'srn') {
test[p] = 34;
}
});
type Test = {
srn: number
}
const test: Test = { srn: 123 };
const isKeyofTest = (s: string): s is keyof Test =>
s === 'srn';
['srn', 'qre'].forEach((p) => {
if (isKeyofTest(p)) {
test[p] = 34;
}
});
For the p variable, the string type is displayed, that is, according to the typescript, it is possible to access an arbitrary field of the test object here.
How to type correctly depends on what should be there. At the moment, you can specify the Record type for test
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question