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

Typscript error when accessing object's value by string index

In javascript, accessing object value via obj.field can be done by obj['field'] too. But produces error in typescript.

function F() {
  const obj = { field: "firstname", title: "First Name", value: 10 };
  let field = "field"
  console.log(obj[field]); // <-- Typescript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ field: string; title: string; value: number; }'
}

How can I cast obj to resolve typescript error?

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 :

You can narrow field as follows:

function F() {
  const obj = { field: 'firstname', title: 'First Name', value: 10 };
  const field: keyof typeof obj = 'field'; // field is narrowed to be a known key of obj instead of 'string'

  console.log(obj[field]); // no type error here
}
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