Home > other >  Cannot find name "T" Typescript
Cannot find name "T" Typescript

Time:02-25

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 ?

CodePudding user response:

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>
  );
};
  • Related