Skip to content
Advertisement

Can I add property to object only if true in typescript?

I have an object:

JavaScript

and I want to add fields base on another object. if they false I don’t want to add this key to the object.

right now I write my code like this:

JavaScript

if I write like this I get the nullable key anyway. no matter if is true or false and I want only if true the key should exist.

JavaScript

So I asking is there a way to write this in better in typescript? something like:

JavaScript

Advertisement

Answer

So I asking is there a way to write this in better in typescript?

Not really, no. What you have with the if statements is probably simplest.

You could use spread notation, like this:

JavaScript

That works because if you spread undefined it doesn’t do anything. But I don’t think I’d call it “better.” 🙂

If the values of your foo fields are always primitives, you could use && but I wouldn’t:

JavaScript

But if the foo fields might be objects, that’s not going to work, and clarity probably suffers anyway. (That “works” for primitives because if you spread a primitive, it gets converted to the equivalent object — 42 becomes new Number(42), in effect — and by default the object types for primitives have no own, enumerable properties, so nothing gets spread.)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement