Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TS type-check error on dynamic key in record

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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) => {});
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading