Javascript 如何在TypeScript中重用参数类型声明
假设我有这样的代码:Javascript 如何在TypeScript中重用参数类型声明,javascript,typescript,vue.js,Javascript,Typescript,Vue.js,假设我有这样的代码: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...item, ...patch
function updateById(
collection: Record<string, any>[],
id: number,
patch: Record<string, any>
): any[] {
return collection.map(item => {
if (item.id === id) {
return {
...item,
...patch
};
}
return item;
});
}
function updateRefById(
collection: Ref<Record<string, any>[]>,
id: number,
patch: Record<string, any>
): void {
collection.value = updateById(collection.value, id, patch);
}
函数updateById(
收集:记录[],
身份证号码:,
补丁:记录
):任何[]{
返回集合.map(项=>{
如果(item.id==id){
返回{
…项目,
…补丁
};
}
退货项目;
});
}
函数updateRefById(
收藏:Ref,
身份证号码:,
补丁:记录
):无效{
collection.value=updateById(collection.value、id、补丁);
}
有一个通用的updateById函数和包装它的更具体的updateRefById。正如您所看到的,类型检查中存在一些重复,因为它们的参数几乎相同
有没有办法让这个更干燥
我唯一能想象的是将所有参数作为一个options对象传递。但我不确定是否要这样做。这可以通过泛型完成,因此可以跳过冗余类型。这需要用变量替换函数声明,在这种情况下不会有太大的改进,因为返回和
集合
参数类型不重复:
type TCollection = Record<string, any>[];
type TUpdateFn<T, U> = (
collection: T,
id: number,
patch: Record<string, any>
) => U;
const updateById: TUpdateFn<TCollection , any[]> = (collection, id, patch) => { ... };
const updateRefById: TUpdateFn<Ref<TCollection>, void> = (collection, id, patch) => { ... };
type TCollection=Record[];
类型TUpdateFn=(
收藏:T,
身份证号码:,
补丁:记录
)=>U;
const updateById:TUpdateFn=(集合、id、补丁)=>{…};
const updateRefById:TUpdateFn=(集合、id、补丁)=>{…};