0

Is there a way in monocle (monocle-ts especially) to change the policy of how to handle missing interposed nodes in a structured data, such as in examples A, B and C below, to create them instead of no-oping? I have a use case where that different behavior is desirable. Can I work within the library to achieve it?

import { Optional } from "monocle-ts";

interface BazMaybe {
  baz?: number;
}

interface BarMaybe {
  bar?: BazMaybe;
}

interface FooMaybe {
  foo?: BarMaybe;
}

const baz = Optional.fromNullableProp<BazMaybe>()("baz");
const bar = Optional.fromNullableProp<BarMaybe>()("bar");
const foo = Optional.fromNullableProp<FooMaybe>()("foo");

const foo_bar_baz = foo.compose(bar).compose(baz);

// A) no op, gives `{}`
console.log(JSON.stringify(foo_bar_baz.set(42)({})));

// B) no op, gives `{"foo":{"bar":{}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: {} } })));

// C) no op, gives `{"foo":{"bar":{}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: { baz: undefined } } })));

// D) ok, finally, gives `{"foo":{"bar":{"baz":42}}}`
console.log(JSON.stringify(foo_bar_baz.set(42)({ foo: { bar: { baz: 0 } } }));

Further, can we define a policy to always replace empties during updates with undefined (recursively) so that the reverse operation is consistent?

// E) ideally, this should give `{}`
console.log(JSON.stringify(foo.compose(bar).modify(
    ( baz, ...rest ) => 
        (rest))({ foo: { bar: { baz: 42} } })));
4

0 回答 0