Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using optional chaining in typescript when using the find by key bracket syntax

I am attempting to use the optional chaining operator on the following:

productPrice1: product.prices["1"]?.amount.amount_1,

The question mark that I have in place ensures that if a child object of key ["1"] doesn't exist it will not fail. However, I would like to do the same if the prices object (the parent object) doesn't exist as well.

prices is an object with child objects that have keys such as "1", "2", "3". I want to first check if prices is null, if not then check if ["1"] exists.

My initial attempt was to try this and it isn't working:

productPrice1: product.prices?["1"]?.amount.amount_1,

I am trying to avoid doing the following and wondering if it is my only option:

productPrice1: product.prices != null ? product.prices?["1"]?.amount.amount_1 : null,
like image 799
Blake Rivell Avatar asked May 12 '26 16:05

Blake Rivell


1 Answers

Assuming your product value is of something like the following type:

declare const product: {
    prices?: Partial<Record<"1" | "2" | "3",
        {
            amount: {
                amount_1: number
            }
        }>>
}

Then you can use optional chaining like this:

const val = {
    productPrice1: product.prices?.["1"]?.amount.amount_1
}

The important piece to note here is that the syntax for optional chaining is always ?. with the dot, even when you aren't using dotted property access. According to the tc39 optional chaining proposal (emphasis added):

The Optional Chaining operator is spelled ?.. It may appear in three positions:

obj?.prop // optional static property access obj?.[expr] // optional dynamic property access func?.(...args) // optional function or method call

Yes, it's weird, and they know it. According to the proposal's FAQ:

obj?.[expr] and func?.(arg) look ugly. Why not use obj?[expr] and func?(arg) as does <language X>?

We don’t use the obj?[expr] and func?(arg) syntax, because of the difficulty for the parser to efficiently distinguish those forms from the conditional operator, e.g., obj?[expr].filter(fun):0 and func?(x - 2) + 3 :1.

Alternative syntaxes for those two cases each have their own flaws; and deciding which one looks the least bad is mostly a question of personal taste. Here is how we made our choice:

  • pick the best syntax for the obj?.prop case, which is expected to occur most often;
  • extend the use of the recognisable ?. sequence of characters to other cases: obj?.[expr], func?.(arg).

As for <language X>, it has different syntactical constraints than JavaScript because of <some construct not supported by X or working differently in X>.

Ok, but I really think that <alternative syntax> is better.

Various alternative syntaxes has been explored and extensively discussed in the past. None of them gained consensus. Search for issues with label “alternative syntax”, as well as issues with label “alternative syntax and semantics” for those that had impact on semantics.

Okay, hope that helps; good luck!

Playground link to code

like image 82
jcalz Avatar answered May 15 '26 06:05

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!