1

Why I get this error message:

Cannot find name "T"

Code:

const List: React.FC<T> = ({ items, render }: {
  items: T[];
  render: (item: T) => React.ReactNode;
}) => {
  return (
    <View>
      { items.map((el ,i) => (
        <Text key={i}>{el}</Text>
      )) }
    </View>
  )
}

What I am doing wrong ?

3
  • Assuming you are trying to make it a type parameter of the function, it should be const List: React.FC = <T>(...). Commented Feb 25, 2022 at 11:23
  • This not working I get unexcepted token error Commented Feb 25, 2022 at 11:30
  • Oh, it needs to be <T,>(...) to avoid ambiguity in the syntax when Typescript generics are mixed with JSX. Commented Feb 25, 2022 at 11:41

1 Answer 1

3

The generic that React.FC accepts is used to type the props object. So instead of inline typing your props, you would create an interface that accepts its own generic:

interface ListProps<T = unknown> {
  items: T[];
  render: (item: T) => React.ReactNode;
}

and then declare the interface that you will pass into the ListProps generic:

interface YourGenericType {
  el: string;
}

To consume these two interfaces together with your component:

const List: React.FC<ListProps<YourGenericType>> = ({ items, render }) => {
  return (
    <View>
      {items.map((el, i) => (
        <Text key={i}>{el}</Text>
      ))}
    </View>
  );
};

Edit: I would also add that unless you need access to an implicit children type, it's recommended that you don't use React.FC as a function type signature. See here for more info. With this in mind, I would type your List component like so:

const List = ({ items, render }: ListProps<YourGenericType>) => {
  return (
    <View>
      {items.map((el, i) => (
        <Text key={i}>{el}</Text>
      ))}
    </View>
  );
};
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.