Skip to content

castMapping

将值转换为映射函数

117 bytes
since v12.2.0

使用方法

通过使用 castMapping 获取映射函数,为您自己的实用函数添加灵活的值映射选项来改进它。

以下类型可以转换为映射函数:

  1. 函数:如果输入是函数,它按原样返回该函数。
  2. 属性名:如果输入是属性名,它返回一个从对象检索该属性值的函数。
  3. Nullish:如果输入是 nullish(null 或 undefined),它返回一个简单返回输入对象本身的函数。
import * as _ from "radashi";
// 使用属性名
const getName = _.castMapping("name");
getName({ name: "Alice" }); // => 'Alice'
// 使用函数
const getLength = _.castMapping((str: string) => str.length);
getLength("Hello"); // => 5
// 使用undefined
const identity = _.castMapping(undefined);
identity({ any: "value" }); // => { any: 'value' }

类型

CastMapping

这是 castMapping 的返回类型。

import * as _ from "radashi";
import type { CastMapping } from "radashi";
const data = { a: 1, b: "2" };
const mapper: CastMapping<typeof data, number> = _.castMapping(
(data) => data.a
);

MappedOutput

正如您在之前的示例中可能注意到的,MappedOutput 类型用于推断映射函数返回的值的类型。

import type { MappedOutput } from "radashi";
type Data = { a: number; b: string };
const test = <T>() => T;
test<MappedOutput<Data, (data: Data) => number>>();
// 是 number
test<MappedOutput<CastMapping<"a">>>();
// 是 number
test<MappedOutput<undefined>>();
// 是 Data

Mapping

您可以使用 Mapping 类型来接受可以传递给 castMapping 的值。

import * as _ from "radashi";
import type { Mapping, MappedOutput } from "radashi";
function mapArray<T, TMapping extends Mapping<T>>(
array: readonly T[],
mapping: TMapping
): MappedOutput<TMapping, T>[] {
return array.map(_.castMapping(mapping));
}

如果您希望映射是可选的,请改用 OptionalMapping 类型。

import type { OptionalMapping, MappedOutput } from "radashi";
function mapArray<T, TMapping extends OptionalMapping<T>>(
array: readonly T[],
mapping?: TMapping
): MappedOutput<TMapping, T>[] {
return array.map(_.castMapping(mapping));
}

词源

起源

术语”castMapping”结合了编程中的两个关键概念:

  1. “Cast”源于编程中的类型转换,涉及将值从一种数据类型转换为另一种数据类型。此过程确保数据采用特定操作的正确格式。

  2. “Mapping”作为名词指的是两个集合元素之间的对应关系,或定义这种对应关系的函数。在编程中,它通常表示将键与值关联的数据结构,或将一组数据转换为另一组数据的函数。

“castMapping”一起描述了一个函数,它接受一个值(可能是函数、属性名或 undefined)并将其转换或”转换”为标准化映射。然后可以使用此结果映射来一致地转换数据,无论初始输入类型如何。该过程通过允许各种输入类型被统一视为数据转换的映射来增强数据操作的灵活性。