Avatar ·

通过字符串键访问对象时出现错误“Element implicitly has an 'any' type”

大家好!我是TypeScript新手,遇到了一个无法理解的错误。我有一个预定义键的对象,想通过来自string类型变量的键获取值。 这是一个简化的例子: ```typescript const userRoles = { admin: '完全访问', editor: '编辑', viewer: '仅查看' }; function getRole(roleName: string) { return userRoles[roleName]; } ``` TypeScript报错: ``` Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ admin: string; editor: string; viewer: string; }'. No index signature with a parameter of type 'string' was found on type '{ admin: string; editor: string; viewer: string; }'. ``` 我明白问题在于我试图用`string`访问一个键为特定字面量(`'admin' | 'editor' | 'viewer'`)的对象。但如果键来自外部源(例如