[英]Javascript Optional chaining doesnt work with template literals
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.其中 variable 是以 A 或 B 作为值的字符串。 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.编辑:我收到“字符串不能用于索引类型项目时尝试使用
data?.[variable]?.itemId
。我现在已经更新了类型。
Edited: Removing type of variable helped in solving above error message.已编辑:删除变量类型有助于解决上述错误消息。
Just wrap the variable inside [
and ]
like: data?.[variable]?.itemId
(it's called Computed Property Names
and it's an es6
feature.)只需将变量包装在
[
和]
中,例如: data?.[variable]?.itemId
(它称为Computed Property Names
,它是es6
功能。)
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.更多: Output 的字符串字面量是一个字符串,所以你可以使用
eval(`data?.${variable}?.itemId`)
来评估它的值。 (Note that using eval
is a bad practice.) (请注意,使用
eval
是一种不好的做法。)
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.在模板中,唯一被视为表达式的东西是
${}
中的东西,因此在您的情况下,您的可选链指示符是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
.使用对象键的可选链接的语法是
data?.['string']?.itemId
,或者如果键存储在变量data?.[variable]?.itemId
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.