简体   繁体   English

Typescript + React:基于其他属性对象键的通用属性

[英]Typescript + React: Generic properties based on keys of other property object

Apologies for the somewhat confusing title.为有点混乱的标题道歉。

I have a React.FC (duck-typed) in a .tsx file with a generic component:我在带有通用组件的.tsx文件中有一个React.FC (鸭子类型):

interface ITimeSeriesProps<PlotNames extends string> {

  /// map from keys to info about a plot
  plots: Record<PlotNames, Plot>,  // actual Plot type unimportant

  /// which ones to show on the plot
  show: PlotNames[]
}

const TimeSeries = <PlotNames extends string>(props: ITimeSeriesProps<PlotNames>) => {
  ...

  return <>
    ...
  </>
}

I can use it like this:我可以这样使用它:

<TimeSeries<"test">
  plots = {
    test: {...}    // correctly types this key
  }
  show: ["test"]   // correctly types this entry
>
</TimeSeries>

However, I would prefer if I didn't have to specify the generic parameter <"test"> , and that it was infered from the keys of the plots Record actual type.但是,如果我不必指定通用参数<"test"> ,并且它是从plots Record实际类型的键推断出来的,我会更喜欢。 Is this possible?这可能吗?

Figured it out.弄清楚了。 Use a Record type as the generic paramater rather than the keys by themselves:使用Record类型作为通用参数而不是键本身:

interface ITimeSeriesProps<PlotNames extends Record<string, Plot>> {
  plots: PlotNames,
  show: (keyof PlotNames)[]
}

const TimeSeries = <PlotNames extends Record<string, Plot>>(props: ITimeSeriesProps<PlotNames>) => {
  ...
}

Usage:用法:

<TimeSeries
  plots = {
    test: {...}    // correctly types this key
  }
  show: ["test"]   // correctly types this entry
>
</TimeSeries>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 打字稿通用函数,它根据其他变量提供组件属性 - Typescript generic function which gives component properties based on other variables 如何使用 function 根据其他属性的值初始化 object 属性? - How to initialize an object property based on the values of other properties using a function? React state object 属性从其他属性计算 - React state object property calculated from other properties 如何在 typescript 中编写通用属性 object - How to write generic properties object in typescript (React-Typescript)如何声明和显示具有未知键数和名称的 object 的泛型类型? - (React-Typescript) how to declare and display generic type of object with unknown number and name of keys? 嵌套对象属性的 Typescript 泛型类型 - Typescript generic type for nested object properties Typescript 验证从传递给通用 React 组件的回调返回的 object 的属性? - Typescript validation for properties of an object returned from a callback passed to a generic React component? Typescript:防止 React 道具 object 的额外键? - Typescript: prevent extra keys for a React prop object? 在React中映射对象键并返回子属性 - Mapping object keys in react and returning child properties 在缺少键/属性的数组中过滤 object - React - Filter object in array that is missing keys/properties - React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM