0

I'm creating a component that takes an arbitrary list of values and a transformer that will render a specific value. The values can be of any type, as the rendering is handler by the transformer, but the compiler is complaining about the generics parameter.

Here is a minimal example:

interface MyListParams<T> {
  values: T[];
  transformer: (value: T) => JSX.Element
}

export const MyList: React.FunctionComponent<MyListParam<T>> = ({

}) => <>
    {values.map(transformer)}
  </>

This code gives me the error Cannot find name 'T'. in code React.FunctionComponent<MyListParam<T>>.

I do realize that I have to tell typescript that this function is using generics, but I fail to find the correct place to do so.

2 Answers 2

2

I don't think there's a way to pass a type to the component when using React.FC, so you can try:

interface MyListParams<T> {
    values: T[];
    transformer: (value: T) => JSX.Element;
}
  
const MyList = <T extends object>(props: PropsWithChildren<MyListParams<T>>) => <></>;
Sign up to request clarification or add additional context in comments.

Comments

0

The generics is on the interface - meaning you want to reuse the interface.

In your example you are using the interface so you need to specify its type:

// T is string
export const MyList: React.FunctionComponent<MyListParams<string>> = ({
values, transformer
}) => <>{values.map(transformer)}</>

If the generics on the function see official examples (not a real use case in function component).

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.