1

I have an object:

const options = {};

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:

const options = {};
if (foo.nullable) options.nullable = true;
if (foo.baz) options.baz = true;
if (foo.bar) options.bar = true;
...

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.

 const options = { nullable: options.nullable }
 // options = { nullable: ... }

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

 const options = { nullable && options.nullable } // should be options = {} if nullable is false. otherwise is options = { nullable: true }
3
  • Maybe use a ternary? const options = nullable && options.nullable ? {nullable:true} : {} Commented Jan 15, 2021 at 10:16
  • How your foo looks? Maybe try if (foo.nullable === true) Commented Jan 15, 2021 at 10:16
  • This has already been answerd stackoverflow.com/questions/11704267/… Commented Jan 15, 2021 at 10:39

1 Answer 1

1

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:

const options = {
    ...(foo.nullable ? {nullable: true} : undefined),
    ...(foo.baz ? {baz: true} : undefined),
    ...(foo.bar ? {bar: true} : undefined),
};

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:

const options = {
    ...foo.nullable && {nullable: true},
    ...foo.bar && {bar: true},
    ...foo.baz && {baz: true},
};

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.)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.