最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - React conditional renderProp names and renderProps definitions with TypeScript - Stack Overflow

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论