When explicitly checking if a property is not a string using a variable key, Typescript throws an error saying
Property 'forEach' does not exist on type 'string'.
let params: Record<string, string | string[]>;
const key = 'test';
// This code snippet works
if (params && typeof params['test'] !== 'string') {
params['test'].forEach((element: string) => {});
}
// However, this code snippet fails
if (params && typeof params[key] !== 'string') {
// Error occurs with message: "Property 'forEach' does not exist on type 'string'."
params[key].forEach((element: string) => {});
}
What is the correct way to type/check that a property is an array and run forEach on it?