简体   繁体   English

在 typescript 上创建具有泛型类型的 function

[英]Create a function with generic type on typescript

I would like to transform this function with generic type我想用泛型类型转换这个 function

const entities = toppings.reduce(
    (entities: { [id: number]: Topping }, topping: Topping) => {
      return {
        ...entities,
        [topping.id]: topping,
      };
    },
    {
      ...state.entities,
    }
  );

Any ideas?有任何想法吗?

If you want to define reduce , then use toppings.reduce<Record<number, Topping>> .如果要定义reduce ,请使用toppings.reduce<Record<number, Topping>>

If you want define callback itself or to stick with Topping then do <T extends Topping = Topping> .如果您想定义回调本身或坚持使用Topping ,请执行<T extends Topping = Topping>

const entities = toppings.reduce(
    <T = Topping>(entities: { [id: number]: T}, topping: T): Record<number, T> => {
      return {
        ...entities,
        [topping.id]: topping,
      };
    },
    {
      ...state.entities,
    }
  );

Are you trying to make a function like this?您是否正在尝试制作这样的 function ?

// TypeScript needs to know that the generic type you are passing has at least the id property
// and that the id property is something you can use as an object key
const process = <T extends { id: string | number }>(
  values: T[],
  // I made it so that you don't need to pass the original entities (state.entities) in your code
  // and for that I need to tell TypeScript that the default value of {} is a map of entities by id
  existingEntities: Record<T['id'], T> = {} as Record<T['id'], T>,
): Record<T['id'], T> => {
  return values.reduce(
    (entities, value: T) => ({
      ...entities,
      [value.id]: value,
    }),
    existingEntities,
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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