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

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

报错:

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Object’.
No index signature with a parameter of type ‘string’ was found on type ‘Object’.

// 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]

参考:https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b

更多推荐