在Reaction类型脚本中推断2个道具之间的泛型类型 [英] Infer generic type between 2 props in React TypeScript
本文介绍了在Reaction类型脚本中推断2个道具之间的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我相信这是可能的,但我还不太擅长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' } ? */
}
} />
这篇关于在Reaction类型脚本中推断2个道具之间的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文