fp-ts Record 模块完全指南:以函数式方式驾驭 TypeScript 的 Record<K, T>
fp-ts Record 模块完全指南:以函数式方式驾驭 TypeScript 的 Record<K, T>
本指南系统讲解 fp-ts 中 Record 模块(fp-ts/Record)的全部能力:如何把 TypeScript 原生对象类型 Record<K, T> 当作一个以 T 为元素的函子(Functor)来处理,覆盖转换、过滤、折叠、实例构造、映射、遍历等六大类操作及全部工具函数。读完本文,你将掌握用不可变、柯里化、可管道化的函数式 API 读写、筛选、聚合与组合对象的高效姿势,并理解每个函数背后的源码实现原理。
模块概览:Record<K, T> 的函数式视角
Record 模块自 fp-ts v2.0.0 起提供,其设计动机在 源码头部注释 与 模块文档 中表述得很清楚:
The
Recordmodule enables dealing with TypeScript'sRecord<K, T>type in a functional way, basically treating it as aFunctorinT.
也就是说,Record<string, A> 可以被看作一个容器类型:键 K 相当于"索引",值 T 是容器内元素。因此你可以对它做 map、filter、reduce、traverse 等容器操作,并且所有操作都遵循不可变原则(返回新对象、不修改原对象)。
从类型系统层面,模块通过 URI = 'Record' 注册进 fp-ts 的 HKT 体系(src/Record.ts#L1288-L1300):
export const URI = 'Record'
export type URI = typeof URI
declare module './HKT' {
interface URItoKind<A> {
readonly [URI]: Record<string, A>
}
}
这使得 Record 能够参与 Functor1、Filterable1、Traversable1 等"类型类实例"的泛型编程(详见 HKT.ts 与 typeclass 文档)。
导入方式
模块通过 src/index.ts#L92 以命名空间形式导出(import * as record from './Record',并在 src/index.ts#L530 暴露为 record)。推荐按需从子路径导入:
import * as R from 'fp-ts/Record'
// 或按函数导入
import { map, filter, getMonoid } from 'fp-ts/Record'
大多数实现委托给了只读版本 src/ReadonlyRecord.ts(如 map、lookup、getEq 等),而 Record 模块在其上补充了可变 Record 特有的空值优化与类型签名。
转换(conversions)
fromEntries
将 Array<[key, value]> 元组数组转换为 Record。重复键由最后一个值决定(last 半群)。
签名(v2.12.0 新增):
export declare const fromEntries: <A>(fa: [string, A][]) => Record<string, A>
示例:
import { fromEntries } from 'fp-ts/Record'
assert.deepStrictEqual(fromEntries([['a', 1], ['b', 2], ['a', 3]]), { b: 2, a: 3 })
源码实现(src/Record.ts#L811):本质是 fromFoldable(Se.last<A>(), A.Foldable)(fa),即用 Semigroup.last 合并重复键、用 Array 的 Foldable 实例做折叠:
export const fromEntries = <A>(fa: Array<[string, A]>): Record<string, A> => fromFoldable(Se.last<A>(), A.Foldable)(fa)
注意 Object.entries 的反向操作不保证键序,而 fromEntries 的结果同样不保证键序,使用时不要依赖键的排列。
toArray
获取 Record 中所有键值对,按键的字母序排序,返回 Array<[key, value]>。
签名(v2.0.0 新增):
export declare const toArray: <K extends string, A>(r: Record<K, A>) => [K, A][]
示例:
import { toArray } from 'fp-ts/Record'
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(toArray(x), [
['a', 'foo'],
['b', false],
['c', 3],
])
源码实现(src/Record.ts#L158-L161):基于 collect(S.Ord) 实现——先按 Ord 对键排序再收集:
export const toArray: <K extends string, A>(r: Record<K, A>) => Array<[K, A]> = /*#__PURE__*/ collect(S.Ord)((k, a) => [k, a])
toEntries
toArray 的别名(v2.12.0 新增,src/Record.ts#L798):
export declare const toEntries: <K extends string, A>(r: Record<K, A>) => [K, A][]
示例与 toArray 完全一致:
import { toEntries } from 'fp-ts/Record'
assert.deepStrictEqual(toEntries({ b: 2, a: 1 }), [['a', 1], ['b', 2]])
过滤(filtering)
compact
压缩一个值为 Option 的 Record:丢弃所有 None,保留 Some 的值。
签名(v2.0.0 新增):
export declare const compact: <A>(fa: Record<string, Option<A>>) => Record<string, A>
示例:
import { compact } from 'fp-ts/Record'
import { option } from 'fp-ts'
assert.deepStrictEqual(compact({ a: option.some('foo'), b: option.none, c: option.some('bar') }), {
a: 'foo',
c: 'bar',
})
filter
给定一个 Predicate(或 Refinement),生成新 Record,只保留值满足谓词的条目。
签名(v2.0.0 新增):
export declare const filter: {
<A, B extends A>(refinement: Refinement<A, B>): (fa: Record<string, A>) => Record<string, B>
<A>(predicate: Predicate<A>): <B extends A>(fb: Record<string, B>) => Record<string, B>
<A>(predicate: Predicate<A>): (fa: Record<string, A>) => Record<string, A>
}
示例:
import { filter } from 'fp-ts/Record'
assert.deepStrictEqual(filter((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), {
a: 'foo',
b: 'bar',
})
filter 既支持普通谓词(Predicate<A>,返回 boolean),也支持类型收窄(Refinement<A, B>),后者能让输出 Record 的值类型自动收窄为 B。
filterMap
用返回 Option 的函数映射 Record,只保留 Some 结果、丢弃 None。
签名(v2.0.0 新增):
export declare const filterMap: <A, B>(f: (a: A) => Option<B>) => (fa: Record<string, A>) => Record<string, B>
示例:
import { filterMap } from 'fp-ts/Record'
import { option } from 'fp-ts'
const f = (s: string) => (s.length < 4 ? option.some(`${s} is short`) : option.none)
assert.deepStrictEqual(filterMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), {
a: 'foo is short',
b: 'bar is short',
})
getWitherable
根据给定的 Ord<string> 生成一个 Witherable1<URI> 实例(v2.11.0 新增)。Witherable 结合了 Traversable 与 Compactable 的能力,可对 Record 执行 wither/wilt 操作。
签名:
export declare const getWitherable: (O: Ord<string>) => Witherable1<URI>
源码实现(src/Record.ts#L1525-L1544):先由 getTraversable(O) 获得遍历能力,再通过 witherDefault(T, Compactable) 与 wiltDefault(T, Compactable)(来自 src/Witherable.ts)装配出完整的 wither/wilt:
export const getWitherable = (O: Ord<string>): Witherable1<URI> => {
const T = getTraversable(O)
return {
URI,
map: _map,
reduce: _reduce(O),
foldMap: _foldMap(O),
reduceRight: _reduceRight(O),
traverse: T.traverse,
sequence: T.sequence,
compact,
separate,
filter: _filter,
filterMap: _filterMap,
partition: _partition,
partitionMap: _partitionMap,
wither: witherDefault(T, Compactable),
wilt: wiltDefault(T, Compactable)
}
}
partition
按 Predicate 把 Record 一分为二,返回 Separated 结构(left 为不满足的,right 为满足的)。
签名(v2.0.0 新增):
export declare const partition: {
<A, B extends A>(refinement: Refinement<A, B>): (fa: Record<string, A>) => Separated<Record<string, A>, Record<string, B>>
<A>(predicate: Predicate<A>): <B extends A>(fb: Record<string, B>) => Separated<Record<string, B>, Record<string, B>>
<A>(predicate: Predicate<A>): (fa: Record<string, A>) => Separated<Record<string, A>, Record<string, A>>
}
示例:
import { partition } from 'fp-ts/Record'
assert.deepStrictEqual(partition((s: string) => s.length < 4)({ a: 'foo', b: 'bar', c: 'verylong' }), {
left: {
c: 'verylong',
},
right: {
a: 'foo',
b: 'bar',
},
})
partitionMap
用返回 Either 的函数映射 Record,把结果分成 Left 与 Right 两个 Record(Separated)。
签名(v2.0.0 新增):
export declare const partitionMap: <A, B, C>(
f: (a: A) => Either<B, C>
) => (fa: Record<string, A>) => Separated<Record<string, B>, Record<string, C>>
示例:
import { partitionMap } from 'fp-ts/Record'
import { either } from 'fp-ts'
const f = (s: string) => (s.length < 4 ? either.right(`${s} is short`) : either.left(`${s} is not short`))
assert.deepStrictEqual(partitionMap(f)({ a: 'foo', b: 'bar', c: 'verylong' }), {
left: {
c: 'verylong is not short',
},
right: {
a: 'foo is short',
b: 'bar is short',
},
})
separate
把一个值为 Either 的 Record 分离为 Lefts 与 Rights(Separated)。
签名(v2.0.0 新增):
export declare const separate: <A, B>(fa: Record<string, Either<A, B>>) => Separated<Record<string, A>, Record<string, B>>
示例:
import { separate } from 'fp-ts/Record'
import { either } from 'fp-ts'
assert.deepStrictEqual(
separate({ a: either.right('foo'), b: either.left('bar'), c: either.right('baz') }),
{
right: {
a: 'foo',
c: 'baz',
},
left: {
b: 'bar',
},
}
)
wilt
wilt 是可管道化的 Witherable 方法(v2.6.5 新增):给定一个返回 Applicative<F> 包装的 Either 的函数,遍历 Record 并在 F 中执行 separate。
签名:
export declare const wilt: PipeableWilt1<'Record'>
源码实现(src/Record.ts#L641-L648):先 traverse(F) 把整个 Record 翻转到 F 内部,再用 F.map(..., separate) 完成分离:
export const wilt: PipeableWilt1<URI> = <F>(F: Applicative<F>) => {
const traverseF = traverse(F)
return (f) => (fa) => F.map(pipe(fa, traverseF(f)), separate)
}
wither
wither 是 wilt 的"单子内 compact"版本(v2.6.5 新增):遍历 Record,对每个元素执行返回 F<Option<B>> 的函数,最后在 F 内 compact 掉 None。
签名:
export declare const wither: PipeableWither1<'Record'>
源码实现(src/Record.ts#L630-L635):
export const wither: PipeableWither1<URI> = <F>(F: Applicative<F>) => {
const traverseF = traverse(F)
return (f) => (fa) => F.map(pipe(fa, traverseF(f)), compact)
}
典型的 wither 场景:异步清洗一批配置项,只保留校验通过的值。
折叠(folding)
折叠类操作都要求先提供一个 Ord<string>,用于把 Record 的条目按键排序后再按序处理——这是 Record 折叠与 Array 折叠的关键差异:Record 本身无序,必须先给定顺序。
foldMap
先映射再折叠:把每个值经 f 映射到 Monoid<M>,再用该 Monoid 的 concat 依次合并(v2.0.0 新增)。
签名:
export declare function foldMap(O: Ord<string>): <M>(M: Monoid<M>) => <A>(f: (a: A) => M) => (fa: Record<string, A>) => M
export declare function foldMap<M>(M: Monoid<M>): <A>(f: (a: A) => M) => (fa: Record<string, A>) => M
第二组重载为废弃用法(省略 Ord,默认使用 S.Ord 字符串字典序);源码中通过 'compare' in O 区分两种调用形态(src/Record.ts#L1193-L1206)。
示例:
import { foldMap } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
import { Monoid } from 'fp-ts/Monoid'
const m: Monoid<string> = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }
const f = (a: number) => `-${a}-`
const x = { c: 3, a: 1, b: 2 }
assert.deepStrictEqual(foldMap(Ord)(m)(f)(x), '-1- -> -2- -> -3-')
getFoldable
根据 Ord 生成一个 Foldable1<URI> 实例(v2.11.0 新增),包含 reduce、foldMap、reduceRight。
签名:
export declare const getFoldable: (O: Ord<string>) => Foldable1<URI>
源码实现(src/Record.ts#L1413-L1418):
export const getFoldable = (O: Ord<string>): Foldable1<URI> => ({
URI,
reduce: _reduce(O),
foldMap: _foldMap(O),
reduceRight: _reduceRight(O)
})
getFoldableWithIndex
生成 FoldableWithIndex1<URI, string> 实例(v2.11.0 新增),在 getFoldable 基础上增加 reduceWithIndex、foldMapWithIndex、reduceRightWithIndex,使折叠回调能拿到当前键(src/Record.ts#L1427-L1435)。
签名:
export declare const getFoldableWithIndex: (O: Ord<string>) => FoldableWithIndex1<URI, string>
reduce
按 Ord 排序后从左到右归约 Record(v2.0.0 新增)。
签名:
export declare function reduce(O: Ord<string>): <A, B>(b: B, f: (b: B, a: A) => B) => (fa: Record<string, A>) => B
export declare function reduce<A, B>(b: B, f: (b: B, a: A) => B): (fa: Record<string, A>) => B
示例:
import { reduce } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(reduce(Ord)([] as string[], (b, a) => [...b, `-${a}-`])(x), [
'-foo-',
'-false-',
'-3-',
])
注意输出顺序为 a → b → c(按键排序),与测试 test/Record.ts 中"乱序输入、排序输出"的断言一致。
reduceRight
与 reduce 相同,但从右往左处理(v2.0.0 新增):按键排序后的逆序(最后一个到第一个)。
签名:
export declare function reduceRight(O: Ord<string>): <A, B>(b: B, f: (a: A, b: B) => B) => (fa: Record<string, A>) => B
export declare function reduceRight<A, B>(b: B, f: (a: A, b: B) => B): (fa: Record<string, A>) => B
示例:
import { reduceRight } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(reduceRight(Ord)([] as string[], (a, b) => [...b, `-${a}-`])(x), [
'-3-',
'-false-',
'-foo-',
])
实例(instances)
本节集中了 Record 在 fp-ts 类型类体系中的全部实例与"实例构造器"(getXxx 系列)。其中 Compactable、Filterable、FilterableWithIndex、Functor、FunctorWithIndex 为直接导出的常量实例(v2.7.0 起提供),而依赖 Ord 的 getFoldable/getTraversable/getWitherable 见对应小节。
Compactable
Compactable1<'Record'> 实例(v2.7.0 新增),提供 compact 与 separate(src/Record.ts#L1441-L1445):
export declare const Compactable: Compactable1<'Record'>
Filterable
Filterable1<'Record'> 实例(v2.7.0 新增),聚合 map、compact、separate、filter、filterMap、partition、partitionMap(src/Record.ts#L1451-L1460):
export declare const Filterable: Filterable1<'Record'>
FilterableWithIndex
FilterableWithIndex1<'Record', string> 实例(v2.7.0 新增),在 Filterable 基础上追加全部 WithIndex 变体(src/Record.ts#L1466-L1480):
export declare const FilterableWithIndex: FilterableWithIndex1<'Record', string>
Functor
Functor1<'Record'> 实例(v2.7.0 新增,src/Record.ts#L1373-L1376):
export declare const Functor: Functor1<'Record'>
FunctorWithIndex
FunctorWithIndex1<'Record', string> 实例(v2.7.0 新增,src/Record.ts#L1400-L1404):
export declare const FunctorWithIndex: FunctorWithIndex1<'Record', string>
getDifferenceMagma
生成一个 Magma<Record<string, A>>,其 concat 等价于 difference(v2.11.0 新增,src/Record.ts#L1633-L1635):
签名:
export declare const getDifferenceMagma: <A>() => Magma<Record<string, A>>
示例:
import { getDifferenceMagma, difference } from 'fp-ts/Record'
import { Magma } from 'fp-ts/Magma'
const r1 = { a: 3, c: 3 }
const r2 = { a: 1, b: 2 }
const m: Magma<Record<string, number>> = getDifferenceMagma<number>()
assert.deepStrictEqual(m.concat(r1, r2), difference(r2)(r1))
assert.deepStrictEqual(m.concat(r1, r2), { c: 3, b: 2 })
getEq
给定基础类型的 Eq<A>,构造 Eq<Record<K, A>>(v2.0.0 新增):
签名:
export declare const getEq: <K extends string, A>(E: Eq<A>) => Eq<Record<K, A>>
示例:
import { getEq } from 'fp-ts/Record'
import { string } from 'fp-ts'
import { Eq } from 'fp-ts/Eq'
const eq: Eq<Record<string, string>> = getEq(string.Eq)
assert.deepStrictEqual(eq.equals({ a: 'foo' }, { b: 'bar' }), false)
assert.deepStrictEqual(eq.equals({ a: 'foo' }, { a: 'foo' }), true)
getEq 要求两边的键集合一致且每个对应键的值都相等(键顺序不影响判断)。
getIntersectionSemigroup
给定基础类型 Semigroup<A>,生成以交集方式拼接的 Semigroup<Record<string, A>>:只保留两个输入共有的键,键的值用基础 Semigroup 合并(v2.11.0 新增,src/Record.ts#L1609-L1614)。
签名:
export declare const getIntersectionSemigroup: <A>(S: Se.Semigroup<A>) => Se.Semigroup<Record<string, A>>
示例:
import { getIntersectionSemigroup } from 'fp-ts/Record'
import { Semigroup } from 'fp-ts/Semigroup'
const sNumber: Semigroup<number> = { concat: (x, y) => x - y }
const sRecord: Semigroup<Record<string, number>> = getIntersectionSemigroup(sNumber)
assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { b: -1 })
getMonoid
给定基础 Semigroup<A>,返回 Monoid<Record<K, A>>:concat 取两个 Record 的并集,重叠键用基础 Semigroup 合并,empty 为 {}(v2.0.0 新增)。
签名:
export declare const getMonoid: <K extends string, A>(S: Se.Semigroup<A>) => Monoid<Record<K, A>>
示例:
import { SemigroupSum } from 'fp-ts/number'
import { getMonoid } from 'fp-ts/Record'
const M = getMonoid(SemigroupSum)
assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 })
getShow
给定 Ord<string> 与基础 Show<A>,生成 Show<Record<string, A>>:输出时按键排序,保证展示结果确定(v2.0.0 新增)。
签名:
export declare function getShow(O: Ord<string>): <A>(S: Show<A>) => Show<Record<string, A>>
export declare function getShow<A>(S: Show<A>): Show<Record<string, A>>
第二组重载为废弃用法(默认 S.Ord)。源码通过 'compare' in O 区分(src/Record.ts#L1319-L1331)。
示例:
import { getShow } from 'fp-ts/Record'
import { Show } from 'fp-ts/Show'
import { Ord } from 'fp-ts/string'
const sNumber: Show<number> = { show: (n: number) => `${n}` }
const sRecord: Show<Record<string, number>> = getShow(Ord)(sNumber)
assert.deepStrictEqual(sRecord.show({ b: 2, a: 1 }), '{ "a": 1, "b": 2 }')
getUnionMonoid
与 getMonoid 语义相同(v2.11.0 新增,src/Record.ts#L1587-L1590):基于 getUnionSemigroup 构造,empty 为 {}:
签名:
export declare const getUnionMonoid: <A>(S: Se.Semigroup<A>) => Monoid<Record<string, A>>
示例:
import { SemigroupSum } from 'fp-ts/number'
import { getUnionMonoid } from 'fp-ts/Record'
const M = getUnionMonoid(SemigroupSum)
assert.deepStrictEqual(M.concat({ foo: 123, bar: 234 }, { foo: 456, baz: 567 }), { foo: 579, bar: 234, baz: 567 })
getUnionSemigroup
给定基础 Semigroup<A>,生成以并集方式拼接的 Semigroup<Record<string, A>>:保留两个输入的全部键,重叠键用基础 Semigroup 合并(v2.11.0 新增,src/Record.ts#L1563-L1568)。
签名:
export declare const getUnionSemigroup: <A>(S: Se.Semigroup<A>) => Se.Semigroup<Record<string, A>>
示例:
import { getUnionSemigroup } from 'fp-ts/Record'
import { Semigroup } from 'fp-ts/Semigroup'
const sNumber: Semigroup<number> = { concat: (x, y) => x - y }
const sRecord: Semigroup<Record<string, number>> = getUnionSemigroup(sNumber)
assert.deepStrictEqual(sRecord.concat({ a: 1, b: 2 }, { b: 3, c: 4 }), { a: 1, b: -1, c: 4 })
对比 getIntersectionSemigroup:交集中 a、c 因不共有而被丢弃;并集中全部保留。
映射(mapping)
flap
给定一个值 a 和一个"函数 Record"(每个值都是函数),把 a 依次应用到每个函数上,得到新的 Record(v2.10.0 新增)。
签名:
export declare const flap: <A>(a: A) => <B>(fab: Record<string, (a: A) => B>) => Record<string, B>
示例:
import { flap } from 'fp-ts/Record'
const fab = { x: (n: number) => `${n} times 2`, y: (n: number) => `${n * 2}` }
assert.deepStrictEqual(flap(3)(fab), {
x: '3 times 2',
y: '6',
})
源码实现(src/Record.ts#L1394):flap 由 src/Functor.ts 的通用 flap_ 基于 Functor 实例派生,并用 /*#__PURE__*/ 标记便于打包器做 tree-shaking:
export const flap = /*#__PURE__*/ flap_(Functor)
map
把 Record 的每个值经函数 f 变换,键保持不变(v2.0.0 新增)。
签名:
export declare const map: <A, B>(f: (a: A) => B) => <K extends string>(fa: Record<K, A>) => Record<K, B>
示例:
import { map } from 'fp-ts/Record'
const f = (n: number) => `-${n}-`
assert.deepStrictEqual(map(f)({ a: 3, b: 5 }), { a: '-3-', b: '-5-' })
测试 test/Record.ts 展示了它与 pipe 的组合用法:
pipe({ k1: 1, k2: 2 }, _.map(U.double)) // { k1: 2, k2: 4 }
遍历(traversing)
遍历类操作把 Record 的遍历过程"提升"到任意 Applicative<F> 中执行,是 fp-ts 中 sequence/traverse 的 Record 版本。
getTraversable
根据 Ord<string> 生成 Traversable1<URI> 实例(v2.11.0 新增),提供 map、reduce、foldMap、reduceRight、traverse、sequence(src/Record.ts#L1489-L1497)。
签名:
export declare const getTraversable: (O: Ord<string>) => Traversable1<URI>
getTraversableWithIndex
生成 TraversableWithIndex1<URI, string> 实例(v2.11.0 新增),额外提供 mapWithIndex、reduceWithIndex、foldMapWithIndex、reduceRightWithIndex、traverseWithIndex(src/Record.ts#L1506-L1519)。
签名:
export declare const getTraversableWithIndex: (O: Ord<string>) => TraversableWithIndex1<URI, string>
底层 _traverseWithIndex(src/Record.ts#L1025-L1048)展示了"按排序键逐条 ap 累积"的经典实现:空 Record 直接 F.of({}),否则从 F.of({}) 开始,对每个键依次 F.map 出"追加一个字段"的函数再 F.ap 到当前结果上。
类型 lambda(type lambdas)
URI 是模块在 fp-ts HKT 体系中的注册标识(v2.0.0 新增,src/Record.ts#L1288-L1294):
export declare const URI: 'Record'
export type URI = typeof URI
配合 declare module './HKT' 的 URItoKind 注册,Record<string, A> 才能作为 Kind<URI, A> 参与 Functor1、Traversable1 等通用算法。
工具函数(utils)
collect
把 Record 映射为 Array:回调接收 (key, value),结果按键的字母序排列(v2.0.0 新增)。
签名:
export declare function collect(
O: Ord<string>
): <K extends string, A, B>(f: (k: K, a: A) => B) => (r: Record<K, A>) => Array<B>
export declare function collect<K extends string, A, B>(f: (k: K, a: A) => B): (r: Record<K, A>) => Array<B>
示例:
import { collect } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
const f = <A>(k: string, a: A) => `${k.toUpperCase()}-${a}`
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(collect(Ord)(f)(x), ['A-foo', 'B-false', 'C-3'])
源码实现(src/Record.ts#L115-L139):先 keys_(O) 得到排序键,再逐键 f(key, r[key]) 收集;无 Ord 重载默认 S.Ord(该重载已废弃)。
deleteAt
删除指定键及其值,返回新 Record;键不存在时原样返回(v2.0.0 新增)。
签名:
export declare function deleteAt<K extends string>(
k: K
): <KS extends string, A>(r: Record<KS, A>) => Record<string extends K ? string : Exclude<KS, K>, A>
示例:
import { deleteAt } from 'fp-ts/Record'
assert.deepStrictEqual(deleteAt('a')({ a: 1, b: 2 }), { b: 2 })
assert.deepStrictEqual(deleteAt('c')({ a: 1, b: 2 }), { a: 1, b: 2 })
源码实现(src/Record.ts#L231-L243):先 _.has.call(r, k) 判断键存在,不存在直接返回原引用;否则 Object.assign({}, r) 浅拷贝后 delete:
export function deleteAt(k: string): <A>(r: Record<string, A>) => Record<string, A> {
return <A>(r: Record<string, A>) => {
if (!_.has.call(r, k)) {
return r
}
const out: Record<string, A> = Object.assign({}, r)
delete out[k]
return out
}
}
difference
两个 Record 的差:取两者条目,去除两个输入中共有的键(以 second 为基准判断,v2.11.0 新增)。
签名:
export declare const difference: <A>(second: Record<string, A>) => (first: Record<string, A>) => Record<string, A>
示例:
import { difference } from 'fp-ts/Record'
assert.deepStrictEqual(difference({ a: 1 })({ a: 1, b: 2 }), { b: 2 })
assert.deepStrictEqual(difference({ a: 3 })({ a: 1, b: 2 }), { b: 2 })
assert.deepStrictEqual(difference({ a: 3, c: 3 })({ a: 1, b: 2 }), { b: 2, c: 3 })
注意第三个例子:first 中的 a: 1 因与 second 的键 a 相同被移除,而 second 独有的 c: 3 被并入结果。
源码实现(src/Record.ts#L995-L1005):对空输入做了快速路径(isEmpty 时直接展开另一侧),避免无谓计算。
elem
给定 Eq<A>,判断 Record 中是否存在等于给定值的条目(v2.0.0 新增)。
签名:
export declare const elem: <A>(E: Eq<A>) => {
(a: A): (fa: Record<string, A>) => boolean
(a: A, fa: Record<string, A>): boolean
}
示例:
import { elem } from 'fp-ts/Record'
import { number } from 'fp-ts'
assert.deepStrictEqual(elem(number.Eq)(123, { foo: 123, bar: 234 }), true)
assert.deepStrictEqual(elem(number.Eq)(-7, { foo: 123, bar: 234 }), false)
every
判断 Record 中所有值是否满足谓词(v2.0.0 新增)。
签名:
export declare const every: {
<A, B extends A>(refinement: Refinement<A, B>): Refinement<Record<string, A>, Record<string, B>>
<A>(predicate: Predicate<A>): Predicate<Record<string, A>>
}
示例:
import { every } from 'fp-ts/Record'
assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: 2 }), true)
assert.deepStrictEqual(every((n: number) => n >= 0)({ a: 1, b: -1 }), false)
filterMapWithIndex
filterMap 的带键版本:回调接收 (key, value),返回 Option<B>,只保留 Some(v2.0.0 新增)。
签名:
export declare const filterMapWithIndex: <K extends string, A, B>(
f: (key: K, a: A) => Option<B>
) => (fa: Record<K, A>) => Record<string, B>
示例:
import { filterMapWithIndex } from 'fp-ts/Record'
import { option } from 'fp-ts'
const f = (key: string, a: number) => (a >= 0 ? option.some(`${key}${a}`) : option.none)
assert.deepStrictEqual(filterMapWithIndex(f)({ a: -1, b: 2, c: 3 }), {
b: 'b2',
c: 'c3',
})
filterWithIndex
filter 的带键版本:谓词接收 (key, value)(v2.0.0 新增)。
签名:
export declare function filterWithIndex<K extends string, A, B extends A>(
refinementWithIndex: RefinementWithIndex<K, A, B>
): (fa: Record<K, A>) => Record<string, B>
export declare function filterWithIndex<K extends string, A>(
predicateWithIndex: PredicateWithIndex<K, A>
): <B extends A>(fb: Record<K, B>) => Record<string, B>
export declare function filterWithIndex<K extends string, A>(
predicateWithIndex: PredicateWithIndex<K, A>
): (fa: Record<K, A>) => Record<string, A>
示例:
import { filterWithIndex } from 'fp-ts/Record'
assert.deepStrictEqual(filterWithIndex((s: string, v: number) => s.length <= 1 && v > 0)({ a: 1, b: -2, ccc: 3 }), {
a: 1,
})
foldMapWithIndex
foldMap 的带键版本:回调接收 (key, value)(v2.0.0 新增)。
签名:
export declare function foldMapWithIndex(
O: Ord<string>
): <M>(M: Monoid<M>) => <K extends string, A>(f: (k: K, a: A) => M) => (fa: Record<K, A>) => M
export declare function foldMapWithIndex<M>(
M: Monoid<M>
): <K extends string, A>(f: (k: K, a: A) => M) => (fa: Record<K, A>) => M
示例:
import { foldMapWithIndex } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
import { Monoid } from 'fp-ts/Monoid'
const m: Monoid<string> = { empty: '', concat: (x: string, y: string) => (x ? `${x} -> ${y}` : `${y}`) }
const f = (k: string, a: number) => `${k}-${a}`
const x = { c: 3, a: 1, b: 2 }
assert.deepStrictEqual(foldMapWithIndex(Ord)(m)(f)(x), 'a-1 -> b-2 -> c-3')
fromFoldable
从可折叠集合(如 Array)的键值对构建 Record,用给定 Magma<A> 合并重复键的值(v2.0.0 新增)。
签名:
export declare function fromFoldable<F extends URIS3, A>(
M: Magma<A>,
F: Foldable3<F>
): <R, E>(fka: Kind3<F, R, E, [string, A]>) => Record<string, A>
export declare function fromFoldable<F extends URIS2, A>(
M: Magma<A>,
F: Foldable2<F>
): <E>(fka: Kind2<F, E, [string, A]>) => Record<string, A>
export declare function fromFoldable<F extends URIS, A>(
M: Magma<A>,
F: Foldable1<F>
): (fka: Kind<F, [string, A]>) => Record<string, A>
export declare function fromFoldable<F, A>(
M: Magma<A>,
F: FoldableHKT<F>
): (fka: HKT<F, [string, A]>) => Record<string, A>
(URIS/URIS2/URIS3 是 fp-ts 对 1~3 个类型参数的 HKT 种类的编码,详见 src/HKT.ts。)
fromFoldableMap
从可折叠集合构建 Record,先映射出 [key, value] 对,再用 Magma 合并重复键(v2.0.0 新增)。
签名:
export declare function fromFoldableMap<F extends URIS3, B>(
M: Magma<B>,
F: Foldable3<F>
): <R, E, A>(fa: Kind3<F, R, E, A>, f: (a: A) => [string, B]) => Record<string, B>
export declare function fromFoldableMap<F extends URIS2, B>(
M: Magma<B>,
F: Foldable2<F>
): <E, A>(fa: Kind2<F, E, A>, f: (a: A) => [string, B]) => Record<string, B>
export declare function fromFoldableMap<F extends URIS, B>(
M: Magma<B>,
F: Foldable1<F>
): <A>(fa: Kind<F, A>, f: (a: A) => [string, B]) => Record<string, B>
export declare function fromFoldableMap<F, B>(
M: Magma<B>,
F: FoldableHKT<F>
): <A>(fa: HKT<F, A>, f: (a: A) => [string, B]) => Record<string, B>
示例(经典的 zipObject 与"按 id 索引用户列表"两种用法):
import { last } from 'fp-ts/Semigroup'
import { Foldable, zip } from 'fp-ts/Array'
import { identity } from 'fp-ts/function'
import { fromFoldableMap } from 'fp-ts/Record'
export const zipObject = <K extends string, A>(keys: Array<K>, values: Array<A>): Record<K, A> =>
fromFoldableMap(last<A>(), Foldable)(zip(keys, values), identity)
assert.deepStrictEqual(zipObject(['a', 'b'], [1, 2, 3]), { a: 1, b: 2 })
interface User {
readonly id: string
readonly name: string
}
const users: Array<User> = [
{ id: 'id1', name: 'name1' },
{ id: 'id2', name: 'name2' },
{ id: 'id1', name: 'name3' },
]
assert.deepStrictEqual(
fromFoldableMap(last<User>(), Foldable)(users, (user) => [user.id, user]),
{
id1: { id: 'id1', name: 'name3' },
id2: { id: 'id2', name: 'name2' },
}
)
第二个例子中,重复的 id1 由 last 半群决定"后者覆盖前者"。
has
判断键是否存在于 Record 中。注意它是 Refinement(k is K),因此不可管道化(v2.10.0 新增)。
签名:
export declare const has: <K extends string>(k: string, r: Record<K, unknown>) => k is K
示例:
import { has } from 'fp-ts/Record'
assert.deepStrictEqual(has('a', { a: 1, b: 2 }), true)
assert.deepStrictEqual(has('c', { a: 1, b: 2 }), false)
intersection
两个 Record 的交集:只组合键相同的条目,键的值用给定 Magma<A> 的 concat 合并(v2.11.0 新增)。
签名:
export declare const intersection: <A>(
M: Magma<A>
) => (second: Record<string, A>) => (first: Record<string, A>) => Record<string, A>
示例:
import { intersection } from 'fp-ts/Record'
import { Magma } from 'fp-ts/Magma'
const m1: Magma<number> = { concat: (x: number, y: number) => x + y }
assert.deepStrictEqual(intersection(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4 })
const m2: Magma<number> = { concat: (x: number) => x }
assert.deepStrictEqual(intersection(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1 })
m2 的 concat 只取左侧,因此 a: 1 保留。
isEmpty
判断 Record 是否为空(v2.0.0 新增):
export declare const isEmpty: <A>(r: Record<string, A>) => boolean
示例:
import { isEmpty } from 'fp-ts/Record'
assert.deepStrictEqual(isEmpty({}), true)
assert.deepStrictEqual(isEmpty({ a: 3 }), false)
isSubrecord
给定 Eq<A>,判断一个 Record 是否包含另一个 Record 的所有键且对应值相等(v2.0.0 新增)。
签名:
export declare const isSubrecord: <A>(E: Eq<A>) => {
(that: Record<string, A>): (me: Record<string, A>) => boolean
(me: Record<string, A>, that: Record<string, A>): boolean
}
示例:
import { isSubrecord } from 'fp-ts/Record'
import { string } from 'fp-ts'
assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'bar', c: 'baz' }), true)
assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', c: 'baz' }), true)
assert.deepStrictEqual(
isSubrecord(string.Eq)({ a: 'foo', b: 'bar', c: 'baz' })({ a: 'foo', b: 'not-bar', c: 'baz' }),
false
)
assert.deepStrictEqual(isSubrecord(string.Eq)({ a: 'foo', b: 'bar' })({ a: 'foo', b: 'bar', c: 'baz' }), false)
这里参数顺序为 isSubrecord(E)(that)(me):me 是"子集",that 是"超集";当 me 含有 that 没有的键(第 4 例)或值不相等(第 3 例)时返回 false。
keys
Record 的键数组,按字母序排序(v2.0.0 新增)。
签名:
export declare const keys: <K extends string>(r: Record<K, unknown>) => K[]
示例:
import { keys } from 'fp-ts/Record'
assert.deepStrictEqual(keys({ c: 1, a: 2, b: 3 }), ['a', 'b', 'c'])
源码(src/Record.ts#L76-L91)用 Object.keys(r).sort(O.compare) 实现,默认使用 S.Ord。
lookup
按键查找值,返回 Option<A>:命中 Some(value),未命中 None(v2.0.0 新增)。
签名:
export declare const lookup: {
(k: string): <A>(r: Record<string, A>) => Option<A>
<A>(k: string, r: Record<string, A>): Option<A>
}
示例:
import { lookup } from 'fp-ts/Record'
import { option } from 'fp-ts'
assert.deepStrictEqual(lookup('b')({ a: 'foo', b: 'bar' }), option.some('bar'))
assert.deepStrictEqual(lookup('c')({ a: 'foo', b: 'bar' }), option.none)
mapWithIndex
map 的带键版本:回调接收 (key, value)(v2.0.0 新增)。
签名:
export declare const mapWithIndex: <K extends string, A, B>(f: (k: K, a: A) => B) => (fa: Record<K, A>) => Record<K, B>
示例:
import { mapWithIndex } from 'fp-ts/Record'
const f = (k: string, n: number) => `${k.toUpperCase()}-${n}`
assert.deepStrictEqual(mapWithIndex(f)({ a: 3, b: 5 }), { a: 'A-3', b: 'B-5' })
modifyAt
对指定键的值应用映射函数;键不存在返回 None,否则返回 Some(新Record)(v2.0.0 新增)。
签名:
export declare const modifyAt: <A>(
k: string,
f: (a: A) => A
) => <K extends string>(r: Record<K, A>) => Option<Record<K, A>>
示例:
import { modifyAt } from 'fp-ts/Record'
import { option } from 'fp-ts'
assert.deepStrictEqual(modifyAt('a', (x: number) => x * 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 }))
assert.deepStrictEqual(modifyAt('c', (x: number) => x * 3)({ a: 1, b: 2 }), option.none)
源码实现(src/Record.ts#L278-L287):updateAt 正是 modifyAt(k, () => a) 的特例:
export const modifyAt =
<A>(k: string, f: (a: A) => A) =>
<K extends string>(r: Record<K, A>): Option<Record<K, A>> => {
if (!has(k, r)) {
return _.none
}
const out: Record<K, A> = Object.assign({}, r)
out[k] = f(r[k])
return _.some(out)
}
partitionMapWithIndex
partitionMap 的带键版本(v2.0.0 新增):
签名:
export declare const partitionMapWithIndex: <K extends string, A, B, C>(
f: (key: K, a: A) => Either<B, C>
) => (fa: Record<K, A>) => Separated<Record<string, B>, Record<string, C>>
示例:
import { partitionMapWithIndex } from 'fp-ts/Record'
import { either } from 'fp-ts'
const f = (key: string, a: number) =>
a >= 0 ? either.right(`${key} is >= 0 (${a})`) : either.left(`${key} is < 0 (${a})`)
assert.deepStrictEqual(partitionMapWithIndex(f)({ a: -1, b: 2, c: 123 }), {
left: {
a: 'a is < 0 (-1)',
},
right: {
b: 'b is >= 0 (2)',
c: 'c is >= 0 (123)',
},
})
partitionWithIndex
partition 的带键版本(v2.0.0 新增):
签名:
export declare function partitionWithIndex<K extends string, A, B extends A>(
refinementWithIndex: RefinementWithIndex<K, A, B>
): (fa: Record<K, A>) => Separated<Record<string, A>, Record<string, B>>
export declare function partitionWithIndex<K extends string, A>(
predicateWithIndex: PredicateWithIndex<K, A>
): <B extends A>(fb: Record<K, B>) => Separated<Record<string, B>, Record<string, B>>
export declare function partitionWithIndex<K extends string, A>(
predicateWithIndex: PredicateWithIndex<K, A>
): (fa: Record<K, A>) => Separated<Record<string, A>, Record<string, A>>
示例:
import { partitionWithIndex } from 'fp-ts/Record'
assert.deepStrictEqual(
partitionWithIndex((key: string, a: number) => key.length <= 1 && a > 0)({ a: -1, b: 2, ccc: 7 }),
{
left: {
a: -1,
ccc: 7,
},
right: {
b: 2,
},
}
)
pop
删除指定键,返回 Option<[被删值, 新Record]>;键不存在返回 None(v2.0.0 新增)。
签名:
export declare function pop<K extends string>(
k: K
): <KS extends string, A>(r: Record<KS, A>) => Option<[A, Record<string extends K ? string : Exclude<KS, K>, A>]>
示例:
import { pop } from 'fp-ts/Record'
import { option } from 'fp-ts'
assert.deepStrictEqual(pop('a')({ a: 1, b: 2, c: 3 }), option.some([1, { b: 2, c: 3 }]))
assert.deepStrictEqual(pop('x')({ a: 1, b: 2, c: 3 }), option.none)
源码实现(src/Record.ts#L304-L313):组合 lookup 与 deleteAt——先查值,命中则返回 [值, deleteAt(k)(r)]:
export function pop(k: string): <A>(r: Record<string, A>) => Option<[A, Record<string, A>]> {
const deleteAtk = deleteAt(k)
return (r) => {
const oa = lookup(k, r)
return _.isNone(oa) ? _.none : _.some([oa.value, deleteAtk(r)])
}
}
reduceRightWithIndex
reduceRight 的带键版本(v2.0.0 新增),按键排序后从右往左处理:
签名:
export declare function reduceRightWithIndex(
O: Ord<string>
): <K extends string, A, B>(b: B, f: (k: K, a: A, b: B) => B) => (fa: Record<K, A>) => B
export declare function reduceRightWithIndex<K extends string, A, B>(
b: B,
f: (k: K, a: A, b: B) => B
): (fa: Record<K, A>) => B
示例:
import { reduceRightWithIndex } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(reduceRightWithIndex(Ord)([] as string[], (k, a, b) => [...b, `${k}-${a}`])(x), [
'c-3',
'b-false',
'a-foo',
])
reduceWithIndex
reduce 的带键版本(v2.0.0 新增),回调接收 (key, acc, value):
签名:
export declare function reduceWithIndex(
O: Ord<string>
): <K extends string, A, B>(b: B, f: (k: K, b: B, a: A) => B) => (fa: Record<K, A>) => B
export declare function reduceWithIndex<K extends string, A, B>(
b: B,
f: (k: K, b: B, a: A) => B
): (fa: Record<K, A>) => B
示例:
import { reduceWithIndex } from 'fp-ts/Record'
import { Ord } from 'fp-ts/string'
const x = { c: 3, a: 'foo', b: false }
assert.deepStrictEqual(reduceWithIndex(Ord)([] as string[], (k, b, a) => [...b, `${k}-${a}`])(x), [
'a-foo',
'b-false',
'c-3',
])
sequence
Record 的"序列化":把"元素是单子(monad)的 Record"翻转成"单子包裹的 Record"。例如把 Record<string, Option<number>> 变为 Option<Record<string, number>>(v2.0.0 新增)。
签名(支持 1~3 阶 HKT 及固定环境 E 的重载):
export declare function sequence<F extends URIS3>(
F: Applicative3<F>
): <K extends string, R, E, A>(ta: Record<K, Kind3<F, R, E, A>>) => Kind3<F, R, E, Record<K, A>>
export declare function sequence<F extends URIS3, E>(
F: Applicative3C<F, E>
): <K extends string, R, A>(ta: Record<K, Kind3<F, R, E, A>>) => Kind3<F, R, E, Record<K, A>>
export declare function sequence<F extends URIS2>(
F: Applicative2<F>
): <K extends string, E, A>(ta: Record<K, Kind2<F, E, A>>) => Kind2<F, E, Record<K, A>>
export declare function sequence<F extends URIS2, E>(
F: Applicative2C<F, E>
): <K extends string, A>(ta: Record<K, Kind2<F, E, A>>) => Kind2<F, E, Record<K, A>>
export declare function sequence<F extends URIS>(
F: Applicative1<F>
): <K extends string, A>(ta: Record<K, Kind<F, A>>) => Kind<F, Record<K, A>>
export declare function sequence<F>(
F: Applicative<F>
): <K extends string, A>(ta: Record<K, HKT<F, A>>) => HKT<F, Record<K, A>>
示例:
import { sequence } from 'fp-ts/Record'
import { option } from 'fp-ts'
import { sequenceS } from 'fp-ts/Apply'
assert.deepStrictEqual(
sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }),
option.some({ a: 1, b: 2 })
)
assert.deepStrictEqual(sequence(option.Applicative)({ a: option.some(1), b: option.none }), option.none)
assert.deepStrictEqual(
sequence(option.Applicative)({ a: option.some(1), b: option.some(2) }),
sequenceS(option.Applicative)({ a: option.some(1), b: option.some(2) })
)
文档与源码均明确:Record 的 sequence 等价于 src/Apply.ts 的 sequenceS——任一元素为 None 时整体为 None。
singleton
创建只含一个键值对的 Record(v2.0.0 新增):
签名:
export declare const singleton: <A>(k: string, a: A) => Record<string, A>
示例:
import { singleton } from 'fp-ts/Record'
assert.deepStrictEqual(singleton('a', 1), { a: 1 })
size
统计 Record 的键值对数量(v2.0.0 新增):
签名:
export declare const size: <A>(r: Record<string, A>) => number
示例:
import { size } from 'fp-ts/Record'
assert.deepStrictEqual(size({ a: true, b: 2, c: 'three' }), 3)
some
判断 Record 中至少一个值满足谓词(v2.0.0 新增):
签名:
export declare const some: <A>(predicate: (a: A) => boolean) => (r: Record<string, A>) => boolean
示例:
import { some } from 'fp-ts/Record'
assert.deepStrictEqual(some((n: number) => n >= 0)({ a: 1, b: -2 }), true)
assert.deepStrictEqual(some((n: number) => n >= 0)({ a: -1, b: -2 }), false)
toUnfoldable
把 Record 展开为任意 Unfoldable 容器(如 array、readonlyArray)的键值对列表,按键字母序(v2.0.0 新增)。
签名:
export declare function toUnfoldable<F extends URIS>(
U: Unfoldable1<F>
): <K extends string, A>(r: Record<K, A>) => Kind<F, [K, A]>
export declare function toUnfoldable<F>(U: Unfoldable<F>): <K extends string, A>(r: Record<K, A>) => HKT<F, [K, A]>
示例:
import { array, readonlyArray } from 'fp-ts'
import { toUnfoldable } from 'fp-ts/Record'
assert.deepStrictEqual(toUnfoldable(array)({ b: 2, a: 1 }), [
['a', 1],
['b', 2],
])
assert.deepStrictEqual(toUnfoldable(readonlyArray)({ b: 2, a: 1 }), [
['a', 1],
['b', 2],
])
源码实现(src/Record.ts#L180-L190):先 toArray(r) 得排序键值对,再用 U.unfold 从索引 0 逐步取出元素。
traverse
把 Record 的每个值经返回 Applicative<F> 的函数变换,并把整个结构"翻转"到 F 内(v2.0.0 新增)。
签名(支持 1~4 阶 HKT 的重载):
export declare function traverse<F extends URIS4>(
F: Applicative4<F>
): <S, R, E, A, B>(
f: (a: A) => Kind4<F, S, R, E, B>
) => <K extends string>(ta: Record<K, A>) => Kind4<F, S, R, E, Record<K, B>>
export declare function traverse<F extends URIS3>(
F: Applicative3<F>
): <R, E, A, B>(f: (a: A) => Kind3<F, R, E, B>) => <K extends string>(ta: Record<K, A>) => Kind3<F, R, E, Record<K, B>>
export declare function traverse<F extends URIS3, E>(
F: Applicative3C<F, E>
): <R, A, B>(f: (a: A) => Kind3<F, R, E, B>) => <K extends string>(ta: Record<K, A>) => Kind3<F, R, E, Record<K, B>>
export declare function traverse<F extends URIS2>(
F: Applicative2<F>
): <E, A, B>(f: (a: A) => Kind2<F, E, B>) => <K extends string>(ta: Record<K, A>) => Kind2<F, E, Record<K, B>>
export declare function traverse<F extends URIS2, E>(
F: Applicative2C<F, E>
): <A, B>(f: (a: A) => Kind2<F, E, B>) => <K extends string>(ta: Record<K, A>) => Kind2<F, E, Record<K, B>>
export declare function traverse<F extends URIS>(
F: Applicative1<F>
): <A, B>(f: (a: A) => Kind<F, B>) => <K extends string>(ta: Record<K, A>) => Kind<F, Record<K, B>>
export declare function traverse<F>(
F: Applicative<F>
): <A, B>(f: (a: A) => HKT<F, B>) => <K extends string>(ta: Record<K, A>) => HKT<F, Record<K, B>>
traverseWithIndex
traverse 的带键版本:回调接收 (key, value)(v2.0.0 新增):
签名:
export declare function traverseWithIndex<F extends URIS4>(
F: Applicative4<F>
): <K extends string, S, R, E, A, B>(
f: (k: K, a: A) => Kind4<F, S, R, E, B>
) => (ta: Record<K, A>) => Kind4<F, S, R, E, Record<K, B>>
export declare function traverseWithIndex<F extends URIS3>(
F: Applicative3<F>
): <K extends string, R, E, A, B>(
f: (k: K, a: A) => Kind3<F, R, E, B>
) => (ta: Record<K, A>) => Kind3<F, R, E, Record<K, B>>
export declare function traverseWithIndex<F extends URIS3, E>(
F: Applicative3C<F, E>
): <K extends string, R, A, B>(
f: (k: K, a: A) => Kind3<F, R, E, B>
) => (ta: Record<K, A>) => Kind3<F, R, E, Record<K, B>>
export declare function traverseWithIndex<F extends URIS2>(
F: Applicative2<F>
): <K extends string, E, A, B>(f: (k: K, a: A) => Kind2<F, E, B>) => (ta: Record<K, A>) => Kind2<F, E, Record<K, B>>
export declare function traverseWithIndex<F extends URIS2, E>(
F: Applicative2C<F, E>
): <K extends string, A, B>(f: (k: K, a: A) => Kind2<F, E, B>) => (ta: Record<K, A>) => Kind2<F, E, Record<K, B>>
export declare function traverseWithIndex<F extends URIS>(
F: Applicative1<F>
): <K extends string, A, B>(f: (k: K, a: A) => Kind<F, B>) => (ta: Record<K, A>) => Kind<F, Record<K, B>>
export declare function traverseWithIndex<F>(
F: Applicative<F>
): <K extends string, A, B>(f: (k: K, a: A) => HKT<F, B>) => (ta: Record<K, A>) => HKT<F, Record<K, B>>
union
两个 Record 的并集:合并全部条目,键相同的用给定 Magma<A> 的 concat 合并(v2.11.0 新增)。
签名:
export declare const union: <A>(
M: Magma<A>
) => (second: Record<string, A>) => (first: Record<string, A>) => Record<string, A>
示例:
import { union } from 'fp-ts/Record'
import { Magma } from 'fp-ts/Magma'
const m1: Magma<number> = { concat: (x: number, y: number) => x + y }
assert.deepStrictEqual(union(m1)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 4, b: 2, c: 3 })
const m2: Magma<number> = { concat: (x: number) => x }
assert.deepStrictEqual(union(m2)({ a: 3, c: 3 })({ a: 1, b: 2 }), { a: 1, b: 2, c: 3 })
源码实现(src/Record.ts#L937-L950):对空输入有快速路径——first 为空直接展开 second,反之展开 first,避免不必要的遍历。
updateAt
替换指定键的值;键不存在返回 None,否则 Some(新Record)(v2.0.0 新增)。
签名:
export declare const updateAt: <A>(k: string, a: A) => <K extends string>(r: Record<K, A>) => Option<Record<K, A>>
示例:
import { updateAt } from 'fp-ts/Record'
import { option } from 'fp-ts'
assert.deepStrictEqual(updateAt('a', 3)({ a: 1, b: 2 }), option.some({ a: 3, b: 2 }))
assert.deepStrictEqual(updateAt('c', 3)({ a: 1, b: 2 }), option.none)
upsertAt
插入或替换键值对:键存在则更新,不存在则新增(v2.10.0 新增,src/Record.ts#L203 直接委托 RR.upsertAt):
签名:
export declare const upsertAt: <A>(k: string, a: A) => (r: Record<string, A>) => Record<string, A>
示例:
import { upsertAt } from 'fp-ts/Record'
assert.deepStrictEqual(upsertAt('a', 5)({ a: 1, b: 2 }), { a: 5, b: 2 })
assert.deepStrictEqual(upsertAt('c', 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 })
废弃区(zone of death)
以下导出自 v2.x 起被标记 @deprecated,均有明确替代品。源码中以 // deprecated 注释块集中管理(src/Record.ts#L1637-L1804),建议新代码不要再使用:
| 废弃导出 | 替代方案 |
|---|---|
~~Foldable~~ |
用 getFoldable 代替(v2.7.0 废弃) |
~~FoldableWithIndex~~ |
用 getFoldableWithIndex 代替(v2.7.0 废弃) |
~~Traversable~~ |
用 getTraversable 代替(v2.7.0 废弃) |
~~TraversableWithIndex~~ |
用 getTraversableWithIndex 代替(v2.7.0 废弃) |
~~Witherable~~ |
用 getWitherable 代替(v2.7.0 废弃) |
~~empty~~ |
直接使用新的 {}(v2.0.0 废弃) |
~~hasOwnProperty~~ |
用 has 代替(v2.0.0 废弃) |
~~insertAt~~ |
用 upsertAt 代替(v2.0.0 废弃) |
~~record~~ |
拆分为小而专的实例(R.Functor、R.Filterable 等),见下方说明(v2.0.0 废弃) |
废弃的 record 组合实例
早期版本导出过一个"全家桶"实例 record,同时具备 FunctorWithIndex、FoldableWithIndex、FilterableWithIndex、TraversableWithIndex、Witherable 全部能力(src/Record.ts#L1775-L1804):
export declare const record: FunctorWithIndex1<'Record', string> &
FoldableWithIndex1<'Record', string> &
FilterableWithIndex1<'Record', string> &
TraversableWithIndex1<'Record', string> &
Witherable1<'Record'>
官方建议(见 模块文档 与源码注释):不要传整体实例,而是按需传小实例。例如函数只需要 Functor 能力时,传 R.Functor 而不是 R.record——这能显著减小类型推导负担与打包体积,也是 fp-ts 2.x 后期推荐的"实例最小化"风格。
关键设计要点与最佳实践
Record的遍历永远需要Ord:reduce、foldMap、collect、getFoldable、getTraversable等都要求先给Ord<string>(或隐式默认S.Ord),因为对象键无序,必须先定序才能保证结果确定性。这也是keys、toArray输出"按键字母序"的原因。- 柯里化 + 管道化:绝大多数函数是柯里化的,天然适配
pipe。测试 test/Record.ts 大量演示了pipe(record, R.map(...))的写法。 - 不可变语义:
deleteAt、modifyAt、pop等返回新对象(Object.assign浅拷贝),原对象不被修改;键不存在时deleteAt直接返回原引用(src/Record.ts#L235-L242),是典型的零拷贝优化。 - 失败用
Option表达:lookup、updateAt、modifyAt、pop对"键不存在"都返回None,避免undefined与null的隐式陷阱,可与 src/Option.ts 的Option组合链无缝衔接。 - 集合代数三件套:
union/intersection/difference(均 v2.11.0 起)配Magma的concat可定制合并策略,getUnionSemigroup/getIntersectionSemigroup/getDifferenceMagma则把它们提升为代数实例。 - 优先小型实例:需要类型类实例时,优先使用
Functor、Filterable、FilterableWithIndex等单一职责实例,或getFoldable(O)、getTraversable(O)、getWitherable(O)这类按需构造的实例,避免使用废弃的record组合实例。
参考资源
- 模块文档:docs/modules/Record.ts.md
- 完整源码实现:src/Record.ts
- 只读委托实现:src/ReadonlyRecord.ts
- 单元测试(含全部 pipeable 用法断言):test/Record.ts
- 模块导出入口:src/index.ts
- 依赖的类型类模块:src/Magma.ts、src/Semigroup.ts、src/Monoid.ts、src/Option.ts、src/Either.ts、src/Ord.ts、src/Show.ts、src/Eq.ts、src/Functor.ts、src/Filterable.ts、src/Traversable.ts、src/Witherable.ts、src/Unfoldable.ts、src/Separated.ts、src/HKT.ts