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?
>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
}