在 React TypeScript 中推断 2 个 props 之间的泛型类型

Mag*_*ull 9 type-inference typescript reactjs

我相信这是可能的,但我不太擅长 TS 中的高级输入(还),所以:

我想让 React 组件在一个 prop 中接受任何对象形状的数组,然后在不同的(事件函数)prop 中发出相同类型。

interface Props {
  data: AnyGenericRow[];
  onRow: (row: AnyGenericRow) => void;
}
Run Code Online (Sandbox Code Playgroud)

我应该如何打字AnyGenericRow才能达到我想要的效果?我想我需要以某种方式推断类型data,然后将该推断的类型应用于签名onRow

用法示例:

const rows: Array<{ foo: 'bar' }> = [];

/* ... */

<Component data={rows} onRow={row => { 
  /* can `row` be detected as a type of { foo: 'bar' } ? */ }
} />
Run Code Online (Sandbox Code Playgroud)

也许这非常简单,但我发现确切地知道要搜索哪些术语来找到它有点棘手。

附加问题:推断的通用行可以扩展组件中的接口吗?也许所需要的只是&它......?

cap*_*ian 16

在这里你有:

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' } ? */
}} />
Run Code Online (Sandbox Code Playgroud)

请记住,您还可以显式设置通用参数Component

<Component<{ foo: 'bar' }> data={[]} onRow={row => {
    /* `row` can be detected as a type of { foo: 'bar' } ? */
}} />
Run Code Online (Sandbox Code Playgroud)