在Typescript中嵌套模板字符串 [英] Nesting template strings in Typescript
问题描述
我正在尝试从对象中检索变量.
I'm trying to retrieve a variable from an object.
cell: (row: any) => `${row.testcolumn}`
我唯一的问题是,我在动态进行操作时不知道什么是"testcolumn".我不确定该怎么做,而我尝试的嵌套模板字符串策略将无法编译.
My only issue is that I don't know what 'testcolumn' is ahead of time as I'm doing this dynamically. I'm not sure what to do, and the nested template string strategy I'm attempting will not compile.
cell: (row: any) => `${row.(`${varString}`)}`
我还尝试过仅使用变量名而不是嵌套模板字符串,但这只是在对象中查找varString值,该值不存在.有什么方法可以使用嵌套文字来将字符串值替换为模板文字,并且它仍在寻找row.testcolumn而不是row.varString?
I've also tried just using the variable name instead of nesting a template string, but that just looks for the varString value in the object, which doesn't exist. Is there any way I can use a nested literal to substitute the string value into the template literal and it still look for row.testcolumn instead of row.varString?
推荐答案
模板文字与常规JS相同.可以使用括号符号row[varString]
动态检索对象属性.
It is same for template literals as for regular JS. Object properties can be retrieved dynamically with bracket notation, row[varString]
.
它将是:
cell: (row: any) => `${row[varString]}`
这篇关于在Typescript中嵌套模板字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!