0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.