Reputation: 11641
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 }
Upvotes: 1
Views: 1723
Reputation: 1074585
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.)
Upvotes: 1