【发布时间】:2019-12-06 19:11:42
【问题描述】:
我想根据提供的键名正确键入以访问对象属性。我想获取下一级对象的键。
我有以下对象,我想从中访问一些数据:
const source = {
sth: {
EXAMPLE: 'this is my example'
},
another: {
TEST: 'this is my test value'
}
};
访问函数:
function getMessage(context : keyof typeof source, msgKey: string) : string {
if(msgKey in source[context]) {
return source[context][msgKey]
}
}
keyof typeof source 我正在获得一级密钥 - 就像一个魅力。
如何获得较低级别的密钥? msgKey: string 当然会出错:
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{示例:字符串; } | {测试:字符串; }'。 在类型“{ 示例:字符串; } | {测试:字符串; }'
当然,通过getMessage('sth', 'EXAMPLE')我想得到'this is my example'
【问题讨论】:
标签: typescript