Skip to content

mfellner/partialize

Repository files navigation

partialize

Travis Codecov codebeat npm license

Turn objects into typesafe proxies to access potentially undefined properties.

Getting started

Let's say you download some unsafe data that should match a given interface:

interface Something {
  foo?: {
    bar?: {
      str?: string;
    };
    baz?: {
      num?: number;
    };
  };
}

const data: Something = await fetch(url).then(r => r.json());

Some properties may be present but others may not!

const str = data.foo!.bar!.str; // OK?
const num = data.foo!.baz!.num; // Error?

Use partialize to wrap an object in a typesafe Proxy:

import partialize, { Part } from '@mfellner/partialize';

const some: Part<Something> = partialize(data);

Now all the declared properties of the object will definitely be defined! That's because each value is turned into an object with all the original properties of that value plus a special $resolve() function. In order to retrieve the original raw value you simply call $resolve():

const str: string | undefined = data.foo.bar.str.$resolve(); // without fallback
const str: string = data.foo.bar.str.$resolve('fallback'); //  with fallback

See test/index.test.ts for some examples.