【问题标题】:Infer generic type between 2 props in React TypeScript在 React TypeScript 中的 2 个 props 之间推断泛型类型
【发布时间】:2021-08-24 09:24:38
【问题描述】:

我相信这是可能的,但我对 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' } ? */ }
} />

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

额外问题:推断的通用行可以扩展组件中的接口吗?也许只需要&amp;它...?

【问题讨论】:

    标签: reactjs typescript type-inference


    【解决方案1】:

    这里有:

    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' } ? */
    }
    } />
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2020-07-23
    • 2017-10-04
    • 2018-01-18
    • 2021-07-28
    • 2020-09-09
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多