3

In Typescript, does anyone know what is this mean?

constructor(obj?:any){
  this.id = obj && obj.id || null;
}

Here is my guessing:

It seems like if (obj is not null) and (obj.id has value), then assign obj.id, otherwise, assign null to this.id??

I looked for around 15-20 places(sites/documents), but I still cannot find the answer. I am sorry that I just start learning TypeScript. Anyone knows any good reference? Thank you for your help in advance!

0

1 Answer 1

4

Your intuition is good! Here's the summary: Operators like if, &&, and || on non-Boolean types in JavaScript cause those types to be evaluated as Boolean. Most commonly, this is used to help figure out if something is null (false), or an object (true).

Note that truthyValue && obj will give you obj, not true, so that syntax is useful for null-coalescing. eg: name = mightBeNull && mightBeNull.name.

A more verbose way to write this constructor would be:

if (obj) {
  this.id = obj.id;
}
else {
  this.id = null;
}

It's something of a code style issue - it's certainly less clear what the intent is, but when you're among many experienced JavaScript programmers, it may make sense to favor short code with patterns people are used to, rather than fully self-documenting routine patterns.

(Finally, note that the above explanation applies equally to JavaScript and TypeScript)

Sign up to request clarification or add additional context in comments.

3 Comments

Minor point: the more verbose way should include a check for obj.id. To see, compare the original code and this verbose code using obj = { id: undefined }. In the original it will be null and in this it will be undefined. Or check obj = {id: false}... original it will be null and this one false.
I understand the point you are trying to make. But null && obj will always give you null.
@Dave That is correct - I've updated the example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.