Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

typescript范型类型推断的问题

有如下 2个react组件

export type DownFile = {
  filename: string;
  fileSize: number;
  process: number;
};

const MapShow = () => {
  const list: DownFile[] = [
    { filename: '下载任务一', fileSize: 100, process: 10 },
    { filename: '下载任务二', fileSize: 100, process: 10 },
    { filename: '下载任务三', fileSize: 100, process: 10 },
  ];

  return (
    <div>
      <AMap />
      <DownLoadList<DownFile>
        dataSource={list}
      />
    </div>
  );
};
interface DownLoadListProps<T> {
  dataSource: T[];
  title?: string;
}

const DownLoadList = <T extends {}>({
  title = '上传列表',
  dataSource,
}: DownLoadListProps<T>) => {
  const [visible, setVisible] = useState(true);

  const column: ColumnProps<DownFile>[] = [
    { title: '文件名', key: 'filename', dataIndex: 'filename' },
    { title: '大小', key: 'fileSize', dataIndex: 'fileSize' },
    {
      title: '进度',
      key: 'process',
      dataIndex: 'process',
      render: (value, record) => <Progress percent={record.process} size="small"/>,
    },
    {
      title: '操作',
      render: (value, record) => (
        <>
          <DeleteOutlined />
        </>
      ),
    },
  ];

  return (
    <Modal
      title={title}
      style={{ top: 20, right: 20 }}
      visible={visible}
      okText={'确认'}
      cancelText={'取消'}
      onOk={() => setVisible(false)}
      onCancel={() => setVisible(false)}
    >
      <Table columns={column} dataSource={dataSource} />
    </Modal>
  );
};

在DownLoadList 组件中,无法推断初T的类型,导致typescript报错

这种形式的 范型组件 改如何 使用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

在使用组件的地方,dataSource传值直接不带着类型应该就可以?ts应该可以根据你传给dataSource的值的类型自动将泛型变量替换为真正传递的值的类型

  <DownLoadList
    dataSource={list}
  />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...