Field lenses in TypeScript
Reid Evans posted a nice little lenses interface and composer for TypeScript. It’s missing a convenience function: a field lens for plain objects. Here is a minimal implementation:
export function field<TRec extends object, K extends keyof TRec = keyof TRec>(fieldName: K): Lens<TRec, TRec[K]> {
return {
get: (rec) => rec[fieldName],
set: (rec, val) => {
const update:Partial<TRec> = {};
update[fieldName] = val;
return Object.assign({}, rec, update);
}
};
}
interface Foo {
bar: number;
baz: string;
}
const fooBar = field<Foo>("bar");