问题描述
我相信这是可能的,但我还不太擅长TS中的高级打字,所以:
我想让Reaction组件在一个道具中接受任何对象形状数组,然后在不同的(事件函数)道具中发出相同的类型。
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' } ? */ }
} />
这可能非常简单,但我发现要确切知道要搜索哪些词语才能找到它,这有点棘手。
额外问题:推断出的泛型行可以扩展组件中的接口吗?也许只需要&
它...?
推荐答案
这里有:
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 => {
/* can `row` be detected as a type of { foo: 'bar' } ? */
}
} />
请记住,您也可以显式设置Component
的泛型参数:
<Component<{ foo: 'bar' }> data={[]} onRow={row => {
/* can `row` be detected as a type of { foo: 'bar' } ? */
}
} />