@mfellner/partialize
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

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.

Package Sidebar

Install

npm i @mfellner/partialize

Weekly Downloads

0

Version

0.3.0

License

MIT

Unpacked Size

10.2 kB

Total Files

7

Last publish

Collaborators

  • mfellner