diff --git a/docs/modules/struct.ts.md b/docs/modules/struct.ts.md index 171a55cd6..91cd56e1d 100644 --- a/docs/modules/struct.ts.md +++ b/docs/modules/struct.ts.md @@ -16,6 +16,7 @@ Added in v2.10.0 - [getAssignSemigroup](#getassignsemigroup) - [utils](#utils) - [evolve](#evolve) + - [prop](#prop) --- @@ -80,3 +81,35 @@ assert.deepStrictEqual( ``` Added in v2.11.0 + +## prop + +Accesses a property of an object + +**Signature** + +```ts +export declare const prop: ( + path: Path +) => ( + obj: keyof A extends never ? B : A +) => Path extends keyof A ? A[Path] : B[Path] +``` + +**Example** + +```ts +import { pipe } from 'fp-ts/function' +import { prop } from 'fp-ts/struct' + +type Person = { + readonly name: string + readonly age: number +} + +const person: Person = { name: 'Jane', age: 62 } +assert.deepStrictEqual(prop('name')(person), 'Jane') +assert.deepStrictEqual(pipe(person, prop('age')), 62) +``` + +Added in v2.11.0 diff --git a/src/struct.ts b/src/struct.ts index 9528ad6b1..4dac13c3f 100644 --- a/src/struct.ts +++ b/src/struct.ts @@ -63,3 +63,27 @@ export const evolve = unknown }>(tr } return out as any } + +/** + * Accesses a property of an object + * + * @example + * import { pipe } from 'fp-ts/function' + * import { prop } from 'fp-ts/struct' + * + * type Person = { + * readonly name: string + * readonly age: number + * } + * + * const person: Person = { name: 'Jane', age: 62 } + * assert.deepStrictEqual(prop('name')(person), 'Jane') + * assert.deepStrictEqual(pipe(person, prop('age')), 62) + * + * @since 2.11.0 + */ +export const prop = (path: Path) => < + B extends { [k in Path]: unknown } +>( + obj: keyof A extends never ? B : A +) => (obj as B)[path] as Path extends keyof A ? A[Path] : B[Path] diff --git a/test/struct.ts b/test/struct.ts index 73d1312aa..89686528c 100644 --- a/test/struct.ts +++ b/test/struct.ts @@ -36,4 +36,15 @@ describe('struct', () => { x.b = 1 U.deepStrictEqual(pipe(x, _.evolve({ b: (b) => b > 0 })), { b: true }) }) + + it('prop', () => { + interface Person { + readonly name: string + readonly age: number + } + + const person: Person = { name: 'Jane', age: 62 } + U.deepStrictEqual(_.prop('name')(person), 'Jane') + U.deepStrictEqual(pipe(person, _.prop('age')), 62) + }) })