https://github.com/mfellner/partialize
Typesafe proxies.
https://github.com/mfellner/partialize
typescript
Last synced: 3 months ago
JSON representation
Typesafe proxies.
- Host: GitHub
- URL: https://github.com/mfellner/partialize
- Owner: mfellner
- License: mit
- Created: 2018-04-06T11:19:08.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2018-08-02T08:03:54.000Z (almost 7 years ago)
- Last Synced: 2025-03-24T02:36:38.318Z (3 months ago)
- Topics: typescript
- Language: TypeScript
- Size: 88.9 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# partialize
[](https://travis-ci.org/mfellner/partialize)
[](https://codecov.io/gh/mfellner/partialize)
[](https://codebeat.co/projects/github-com-mfellner-partialize-master)
[](https://www.npmjs.com/package/@mfellner/partialize)
[](https://choosealicense.com/licenses/mit)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:
```typescript
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!
```typescript
const str = data.foo!.bar!.str; // OK?
const num = data.foo!.baz!.num; // Error?
```Use **partialize** to wrap an object in a typesafe [Proxy](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy):
```typescript
import partialize, { Part } from '@mfellner/partialize';const some: Part = 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()`:
```typescript
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](test/index.test.ts) for some examples.