我相信这是可能的,但我不太擅长 TS 中的高级输入(还),所以:
我想让 React 组件在一个 prop 中接受任何对象形状的数组,然后在不同的(事件函数)prop 中发出相同类型。
interface Props {
data: AnyGenericRow[];
onRow: (row: AnyGenericRow) => void;
}
我应该如何打字AnyGenericRow
达到我想要的目的?我想我需要从中推断出类型data
以某种方式然后将该推断的类型应用于onRow
签名。
用法示例:
const rows: Array<{ foo: 'bar' }> = [];
/* ... */
<Component data={rows} onRow={row => {
/* can `row` be detected as a type of { foo: 'bar' } ? */ }
} />
也许这非常简单,但我发现确切地知道要搜索哪些术语来找到它有点棘手。
附加问题:推断的通用行可以扩展组件中的接口吗?也许所需要的只是&
it...?
在这里你有:
import React from 'react'
interface Props<T> {
data: T[];
onRow: (row: T) => void;
}
const rows: Array<{ foo: 'bar' }> = [];
function Component<T>(props: Props<T>) {
return null
}
<Component data={rows} onRow={row => {
/* `row` can be detected as a type of { foo: 'bar' } ? */
}} />
请记住,您还可以设置通用参数Component
明确地:
<Component<{ foo: 'bar' }> data={[]} onRow={row => {
/* `row` can be detected as a type of { foo: 'bar' } ? */
}} />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)