简体   繁体   中英

How to reuse argument type declaration in TypeScript

Let's say I have code like this:

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);
}

There's a generic updateById function and more specific updateRefById that wraps it. As you can see, there's some duplication in type checking as they have almost the same arguments.

Is there any way to make this more DRY?

The only thing I can imagine is passing all the arguments as one options object. But I'm not sure if I want to do that.

This can be done with a generic, so redundant types can be skipped. This will require to replace function declarations with variables and won't be a big improvement in this case because return and collection parameter types aren't duplicated:

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) => { ... };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM