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.
Just 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With