Appearance
TypeScript 工具类型
一、Mapper
Array.prototype.map()
方法,需要我们传递一个 callbackFn
参数,这个参数是一个函数,有着 3
个参数,第1
个参数是当前数据项,第2
个参数是当前数据项的索引,第3
个参数则是当前数组。
我们可以使用 type
关键字去声明这个类型:
代码示例
typescript
type Mapper<T, R = any> = (item: T, index: number, array: Array<T>): R;
使用场景
我们有一个列表,需要根据不同的符号进行分组,并且不与视图代码相耦合。
首先我们有一个数据项 Item
:
typescript
interface Item {
id: number
}
我们想要在数据项 Item
的基础上添加一个 group
属性,提供给视图使用:
typescript
interface GroupItem extends Item {
group: number
}
然后我们声明一个方法:
typescript
type GroupMapper = Mapper<Item, GroupItem>
function getItems(mapper: GroupMapper): Array<GroupItem> {
const items: Array<Item> = [
{
id: 1,
},
{
id: 2
},
{
id: 3
},
];
return items.map(mapper);
}
在组件内部使用列表:
typescript
// 根据不同的符号实现 GroupMapper,这是一个简单的 GroupMapper 实现
const defaultMapper: GroupMapper = (item, index) => {
return {...item, group: index < 2 ? 0: 1 }
}
const list = getItems(defaultMapper)
// 消费 list