admin管理员组文章数量:1332628
I am trying to apply template literal with optional chaining.
type Item = {
itemId:number,
price: number};
type ItemType = {
A:Item,
B:Item
};
const data : ItemType = {
A:{itemId:1, price:2},
B:{itemId:2, price:3}
};
let Itemid = `data?.${variable}?.itemId`
where variable is a string with A or B as value. I am not sure if optional chaining and template literals are supported together. Any Leads is appreciated.
Edited:
I am receiving "string cant be used to index type Item' when tried with data?.[variable]?.itemId
. I have updated with type now.
Edited: Removing type of variable helped in solving above error message.
I am trying to apply template literal with optional chaining.
type Item = {
itemId:number,
price: number};
type ItemType = {
A:Item,
B:Item
};
const data : ItemType = {
A:{itemId:1, price:2},
B:{itemId:2, price:3}
};
let Itemid = `data?.${variable}?.itemId`
where variable is a string with A or B as value. I am not sure if optional chaining and template literals are supported together. Any Leads is appreciated.
Edited:
I am receiving "string cant be used to index type Item' when tried with data?.[variable]?.itemId
. I have updated with type now.
Edited: Removing type of variable helped in solving above error message.
Share Improve this question edited Aug 5, 2020 at 15:31 Dy4 asked Aug 4, 2020 at 22:29 Dy4Dy4 7271 gold badge12 silver badges22 bronze badges2 Answers
Reset to default 6Just wrap the variable inside [
and ]
like: data?.[variable]?.itemId
(it's called Computed Property Names
and it's an es6
feature.)
Full code:
let data = {
A:{itemId:1, price:2},
B:{itemId:2, price:3}
}
let variable = 'A'
let Itemid = data?.[variable]?.itemId
More:
Output of string literal is an string, so you can use eval(`data?.${variable}?.itemId`)
to evaluate the value of it. (Note that using eval
is a bad practice.)
However In your case, There is no need to use template literals. Just use []
as described above.
In a template the only stuff that is treated as an expression is stuff within ${}
, so in your case your optional chain indicators are part of the string, not part of the expression that will be interpolated into the string.
The syntax for optional chaining using objects keys is data?.['string']?.itemId
, or if the key is stored inside a variable data?.[variable]?.itemId
.
本文标签: reactjsJavascript Optional chaining doesnt work with template literalsStack Overflow
版权声明:本文标题:reactjs - Javascript Optional chaining doesnt work with template literals - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742235035a2437922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论