繁体   English   中英

带有 React 的打字稿,推断作为道具传递的数组类型

[英]Typescript with React, infer type of array passed as prop

我有这个组件:

import React from 'react'

export interface IForEachProps {
  each: any[]
  children: <T>(item: T, index: number) => JSX.Element
  given?: boolean
  key?: (item: any) => any
}

export const For: React.FC<IForEachProps> = ({ each, children, key, given = true }) => {
  if (!given) return null

  return (
    <>
      {each.map((item, index) => (
        <React.Fragment key={key ? key(item) : index}>{children(item, index)}</React.Fragment>
      ))}
    </>
  )
}

我试图推断each道具的类型没有成功,因为这可能是任何数组。 我想要的是,看下面的例子是让编译器从输入数组中推断出回调中的参数实际上是一个字符串。

const list: string[] = ['hello']
<For each={list}>
  {(item) => (
    <div>{item.length}</div>
  )}
</For>

解决了。 必须将组件转换为函数组件才能正确使用泛型。

import React from 'react'

export interface IForEachProps<T> {
  each: Array<T>
  children: (item: T, index: number) => JSX.Element
  given?: boolean
  key?: (item: any) => any
}

export function For<T>({ each, children, key, given = true }: IForEachProps<T>) {
  if (!given) return null

  return (
    <>
      {each.map((item, index) => (
        <React.Fragment key={key ? key(item) : index}>{children(item, index)}</React.Fragment>
      ))}
    </>
  )
}

肯定行不通。 TS 看到each: any[] 这意味着“忘记你对那种类型的任何了解”。 要使其正常工作,您必须为此接口提供泛型类型。 因此,您将强制 TS 找到该数组的确切类型:

export interface IForEachProps<Item> {
  each: Array<Item>
  children: (item: Item, index: number) => JSX.Element
  given?: boolean
  key?: (item: Item) => string | number

我也强烈建议避免使用“任何”类型。 它总是破坏 Typescript 的核心思想。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM