Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add object.prop function #1454

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 33 additions & 0 deletions docs/modules/struct.ts.md
Expand Up @@ -16,6 +16,7 @@ Added in v2.10.0
- [getAssignSemigroup](#getassignsemigroup)
- [utils](#utils)
- [evolve](#evolve)
- [prop](#prop)

---

Expand Down Expand Up @@ -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 extends keyof A extends never ? string : keyof A, A>(
path: Path
) => <B extends { [k in Path]: unknown }>(
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
24 changes: 24 additions & 0 deletions src/struct.ts
Expand Up @@ -63,3 +63,27 @@ export const evolve = <A, F extends { [K in keyof A]: (a: A[K]) => 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 extends keyof A extends never ? string : keyof A, A>(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]
11 changes: 11 additions & 0 deletions test/struct.ts
Expand Up @@ -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)
})
})