lens.ts
TypeScript Lens implementation with object property proxy
Lens?
Lens is composable abstraction of getter and setter. For more detail of Lens, I
recommend reading the following documents.
Install
Via npm:
$ npm i lens.ts
Usage
type Person = {
name: string,
age: number,
accounts: Accounts,
};
type Accounts = {
twitter?: string,
facebook?: string,
};
const azusa: Person = {
name: 'Nakano Azusa',
age: 15,
accounts: {
twitter: '@azusa',
},
};
const personL = id<Person>();
personL.name;
personL.accounts;
personL.accounts.twitter;
key<Person>()('name');
key<Person>()('accounts')._(key<Accounts>()('twitter'));
getl(personL.accounts.twitter)(azusa);
setl(
personL.name,
'中野梓',
)(azusa);
updatel(
personL.age,
x => x + 1,
)(azusa);
You can find the same code in test/test.ts
API
lens.ts
exports the followings:
import {
Lens,
LensInternal,
lens,
id,
key,
getl,
setl,
updatel,
} from 'lens.ts';
Lens
The type Lens
is just LensInternal
+ property proxy.
type Lens<T, U> = {
readonly [K in keyof U]: Lens<T, U[K]>;
} & LensInternal<T, U>;
Example:
let lens1: Lens<T, U>;
lens.prop1;
LensInternal
LensInternal
provides the compose function _()
for two lenses.
class LensInternal<T, U> {
_<V>(other: Lens<U, V>): Lens<T, V>;
}
Example:
let lens1: Lens<T, U>;
let lens2: Lens<U, V>;
lens1._(lens2);
lens
Create a lens with a getter and a setter.
function lens<T, U>(
get: (from: T) => U,
set: (val: U) => (from: T) => T,
): Lens<T, U>;
id
Create an identity lens with an object type.
function id<T>(): Lens<T, T>;
Example:
let personL = id<Person>();
key
Create a key lens for an object.
function key<T>(): <K extends keyof T>(k: K): Lens<T, T[K]>;
Example:
let personNameL = key<Person>()('name');
getl
getl
is for get lens. It retrives a value from a lens with a target object.
function getl<T, U>(lens: Lens<T, U>): (target: T) => U;
Example:
let p: Person = { name: 'Azusa' };
getl(personNameL)(p);
setl
setl
is for set lens. It sets a value of a lens with a target object.
function setl<T, U>(lens: Lens<T, U>, val: U): (target: T) => T
Example:
setl(personNameL, 'Yui')(p);
updatel
updatel
is for update lens. It updates a value of a lens by a function, with a target object.
function updatel<T, U>(lens: Lens<T, U>, f: (val: U) => U): (target: T) => T
Example:
updatel(personNameL, name => 'Hirasawa ' + name)(p);
License
MIT