Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index

For anyone who stumbles upon this in the future:

If you’re getting the TypeScript error

‘…expression of type string cannot be used to index…’

then simply specify that the ‘expression of type string’ is a key of the type of that object. For example,

const someObj:ObjectType = data;
const field = 'username';

// This gives an error
const temp = someObj[field];

// Solution 1: When the type of the object is known
const temp = someObj[field as keyof ObjectType]

// Solution 2: When the type of the object is not known
const temp = someObj[field as keyof typeof someObj]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)