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!

toskv
  • 30,680
  • 7
  • 72
  • 74
George Huang
  • 2,504
  • 5
  • 25
  • 47

1 Answers1

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)

Katana314
  • 8,429
  • 2
  • 28
  • 36
  • 1
    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`. – David Sherret Mar 21 '16 at 20:57
  • I understand the point you are trying to make. But `null && obj` will always give you `null`. – Dave Feb 21 '17 at 17:12
  • @Dave That is correct - I've updated the example. – Katana314 Feb 21 '17 at 19:55