Typesafe proxies.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
test
.gitignore
.npmignore
.travis.yml
LICENSE
README.md
index.ts
package.json
tsconfig.json
tslint.json
yarn.lock

README.md

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.