MHebes
MHebes

Reputation: 3247

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:

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. Is this possible?

Upvotes: 0

Views: 33

Answers (1)

MHebes
MHebes

Reputation: 3247

Figured it out. Use a Record type as the generic paramater rather than the keys by themselves:

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>

Upvotes: 1

Related Questions