1

One question for some reason I can't figure out how to do it. I have 2 objects and need to use optional operator to get value in typescript. I can break them into 2 line but I am wondering how can I do in one line code?

// in python
car = {
  "brand": "Ford",
}
name = {
  "brand": "Ford",
}

x, y = car.get("price", 150), name.get('print', 200)
print(x, y)

// Something like this?
const {price: carPrice  = 150, price: namePrice =200} = {car?.price, name?.price}

//It works but I would like to be one line code
const carPrice = car?.price || 150
const namePrice =  name?.price || 200
1
  • 1
    I feel like you're abusing syntax to achieve superficial brevity. @Psidom shows you how you can write it but I don't think you should. Commented Jul 31, 2021 at 22:53

1 Answer 1

2

Tuple destructure would be something similar:

const [ carPrice, namePrice ] = [ car1?.price || 150, name?.price || 200 ]

Or to be more precise, use ?? instead of ||:

const [ carPrice, namePrice ] = [ car1?.price ?? 150, name?.price ?? 200 ]
Sign up to request clarification or add additional context in comments.

2 Comments

There is also the newer ?? operator that can be used. As well as const [ carPrice = 150, namePrice = 200 ] = [ car1?.price, name?.price ]
@VLAZ Wow, good to know that. ?? looks awesome.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.