define accessors for an object on another object
🔧 Install · 🧩 Example · 📜 API docs · 🔥 Releases · 💪🏼 Contribute · 🖐️ Help
$ npm i define-accessors
Defines accessors for a source object on a target object.
Example; all values reflected on source:
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:
const target = {}
const source = {
foo: 'a prop',
}
const other: Record<string, unknown> = {
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)
target
T The target object to define accessors onsource
S The source object where the actual values arepropertyDescriptorFactory
function (key: any, source: S): PropertyDescriptor A function that returns a custom property descriptor for the given key (optional, defaultcreatePropertyDescriptor
)
Returns any The target object but with its type intersected with the source's type
All contributions are welcome!
MIT © 2021 stagas