更改对象形状后,Typescript泛型类型推断对于函数而言为“ any”

时间:2019-07-09 16:56:41

标签: typescript type-inference typescript-generics

在打字稿中,更改功能对象形状后是否可以推断功能参数? 这里的想法是从功能参数动态生成redux动作创建者类型。除非您不需要使用泛型类型,否则通常这是可行的。在下面的示例中,我想生成动作有效负载

export function createActionFactory<
  R extends string,
  T extends any[],
  P extends object
>(type: R, payloadCreator: (...args: T) => P) {
  const actionCreator = (...args: T) => {
    const payload = payloadCreator(...args);

    return { type, payload };
  };

  // comment to get proper type inference
  actionCreator.toString = () => type;

  return actionCreator;
}

// Let's assume react component
type ComponentType<P = {}> = { props: P };
const ModalComponent: ComponentType<{ foo: string, closeModal?: () => void }> = { props: { foo: "bar" } };

const show = createActionFactory(
  "SHOW",
  <T extends { closeModal?: () => void }>(
    component: ComponentType<T>,
    props: Omit<T, "closeModal">
  ) => ({ component, props })
);

// should fail as `quz` is not in the props
show(ModalComponent, { quz: "bar" });

打字机游乐场link

0 个答案:

没有答案