A
A
Alexander Makarov2021-08-24 17:02:42
typescript
Alexander Makarov, 2021-08-24 17:02:42

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

2 answer(s)
D
Dmitry Belyaev, 2021-08-24
@bingo347

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;
  }
});

Option 2:
type Test = {
  srn: number
}

const test: Test = { srn: 123 };

['srn', 'qre'].forEach((p) => {
  if (p === 'srn') {
    test[p] = 34;
  }
});

Option 3:
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;
  }
});

https://www.typescriptlang.org/play?#code/PTAEEYCg...

A
Alexandroppolus, 2021-08-24
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question