[英]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.