Skip to content

Type is lost when using loadable in generic #1018

Open
@iRuj80

Description

@iRuj80

example:

List.tsx

type Props<T> = {
  dataSource: T[]
  rowKey?: ((item: T) => Key) | keyof T
  renderItem: (item: T, index: number) => ReactNode
}

const List = <T,>({
  dataSource = [],
  rowKey,
  ...otherProps
}: Props<T>) => {

  const items = dataSource.map((item: T, index: number) =>
    return (
      <li key={index}>
        {renderItem(item, index)}
      </li>
    )
  )

  return (
    <ul
      {...otherProps}
    >
      {items}
    </ul>
  )
}

index.ts

import loadable from '@loadable/component'

// option 1
const List = loadable(() => import(/* webpackChunkName: "List" */ './List')) - type T is lost -> becomes unknown

// but! if it doesn't get lost like that

// option 2
const List = <T>() => loadable <import('./List').ListProps<T>> (() => import(/* webpackChunkName: "List" */ './List'))

SomeoneComponent.tsx

import List from './index'

type TListItem = {
  iconSize: number;
  title: string;
  label: string;
}

const dataSource: TListItem[]  = Array.from({ length: 10 }).map((_, index) => ({
  iconSize: 10,
  title: `Item ${index}`,
  label: `Label ${index}`,
}))

// if i use the option 2
const ListTest = List<TListItem>()

<ListTest 
  dataSource={dataSource}
  rowKey="label"
  renderItem={(item: TListItem) => <ListItem {...item}/>}
/>

I attached a screenshot of what vscode writes if I use option 1

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions