0.3.0 • Published 7 years ago

@mfellner/partialize v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 years ago

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.

0.3.0

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.0

7 years ago