An open API service indexing awesome lists of open source software.

https://github.com/stagas/define-accessors

define accessors for an object on another object
https://github.com/stagas/define-accessors

accessors getters setters

Last synced: over 1 year ago
JSON representation

define accessors for an object on another object

Awesome Lists containing this project

README

          

define-accessors


define accessors for an object on another object


🔧 Install
· 🧩 Example
· 📜 API docs
· 🔥 Releases
· 💪🏼 Contribute
· 🖐️ Help

***

## Install

```sh
$ npm i define-accessors
```

## API

#### Table of Contents

* [defineAccessors](#defineaccessors)
* [Parameters](#parameters)

### defineAccessors

[src/index.ts:59-72](https://github.com/stagas/define-accessors/blob/95f6e9401b67076377588e17927a3a3c968be44f/src/index.ts#L59-L72 "Source code on GitHub")

Defines accessors for a source object on a target object.

Example; all values reflected on source:

```ts
const target = {}
const source = {
foo: 'a prop',
bar: 'another',
zoo: 10,
}
const typed = defineAccessors(target, source)
expect(typed).toBe(target)
expect(typed.foo).toBe(source.foo)
expect(typed.bar).toBe(source.bar)
expect(typed.zoo).toBe(source.zoo)

typed.foo = 'something else'
expect(typed.foo).toEqual('something else')
expect(source.foo).toEqual('something else')
```

Example; all values reflected on `other` using a custom property descriptor factory:

```ts
const target = {}
const source = {
foo: 'a prop',
}
const other: Record = {
foo: 'something else',
}
const typed = defineAccessors(target, source, (key: string) => ({
enumerable: true,
get() {
return other[key]
},
set(value: never) {
other[key] = value
},
}))
expect(typed).toBe(target)
expect(typed.foo).toBe(other.foo)
```

#### Parameters

* `target` **T** The target object to define accessors on
* `source` **S** The source object where the actual values are
* `propertyDescriptorFactory` **function (key: any, source: S): PropertyDescriptor** A function that returns a custom property descriptor for the given key (optional, default `createPropertyDescriptor`)

Returns **any** The target object but with its type intersected with the source's type

## Contribute

[Fork](https://github.com/stagas/define-accessors/fork) or
[edit](https://github.dev/stagas/define-accessors) and submit a PR.

All contributions are welcome!

## License

MIT © 2021
[stagas](https://github.com/stagas)