admin管理员组

文章数量:1391929

I have this union type:

type RenderPropNames = "renderPropName1" | "renderPropName2" | "renderPropName3";

and a component interface:

interface ComponentProps<T extends string> {
  useRenderPropNames?: (T | RenderPropName)[];
  renderProps: T extends RenderPropName
    ? Partial<Record<T, RenderPropFunction>>
    : Required<Record<T, RenderPropFunction>> & <Partial<Record<T, RenderPropFunction>>
}

component is defined as

export const Component = <T extends string>(props: ComponentProps<T>) => {...} 

The usage of component is as such:

<Component
    useRenderPropNames:{["renderPropName1", "renderPropName2]}
/>

I want to cover these three cases with TS:

  1. If you use one of default renderPropName (or don't use them at all as all will be used) in the list of props you should be able to override it in 'renderProps' but not required to,
  2. If you didn't specify the default renderPropName in the list of props you should not be able to override it in 'renderProps' as it won't be rendered anyway,
  3. If you add custom renderPropName (which you can) you are required to add 'renderProps' for it,

It all works except one case, where I use default and custom renderPropNames in 'useRenderProps' TS will force me to define renderProps for the custom ones and allow me to override the specified defaults but also will not permit usage of not defined defaults in the 'useRenderProps'. This is the case I cannot cover:

<Component
    useRenderPropNames:{["renderPropName1", "renderPropName2", "customPropName"]}
    renderProps:{{
      // this is required
      customPropName: () => <div>custom</div>,
      // this is optional
      renderPropName1: () => <div>first</div>,
      // this should not be an error
      renderPropName3: () => <div>was not defined and can't be used</div>
    }}
/>

I can't figure out how to cover the last case

本文标签: reactjsReact conditional renderProp names and renderProps definitions with TypeScriptStack Overflow