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
.