Typescript throws an error Property 'forEach' does not exist on type 'string'.
when explicitly checking if property is not a string using a variable key.
let params: Record<string, string | string[]>;
const key = 'test';
// This works
if (params && typeof params['test'] !== 'string') {
params['test'].forEach((element: string) => {});
}
// This fails
if (params && typeof params[key] !== 'string') {
// FAILS with "Property 'forEach' does not exist on type 'string'."
params[key].forEach((element: string) => {});
}
How should I type/check that a property is an array and forEach can run?
CodePudding user response:
Typescript compiler do not understood this patterns cause you can technically modify params[key]
value anytime. So typeguard does not work in this case. At least that was the reason with older typescript version, maybe there is other way now.
To fix that you can assign params[key]
to variable and then do the checks:
let params: Record<string, string | string[]> = {}
const key = 'test';
const value = params[key]
if (typeof value !== 'string') {
value.forEach((element: string) => {});
}