I'm new to typescript and I have this trivial error.
(property) data: menuItems[] Type '{ data: menuItems[]; }' is not assignable to type 'IntrinsicAttributes & menuItems[]'. Property 'data' does not exist on type 'IntrinsicAttributes & menuItems[]'.ts(2322)
Here is code: https://codesandbox.io/s/data-is-not-a-function-ju21g6?file=/src/Settings.tsx
And here is another combined with the first one https://codesandbox.io/s/data-is-not-a-function-ju21g6?file=/src/TreeSettings.tsx:256-320
interface IMenuItems {
name: string;
level: number;
id: number;
pid: number;
children?: any[];
}
const Settings = () => {
const { flattenarr, zerotreetoarr } = useConvertTree();
const [data, setData] = useState<menuItems[]>([]);
useEffect(() => {
zerotreetoarr(tree.children as [], [0]);
setData(flattenarr);
}, []);
return <TreeSettings data={data} />;
};
export interface IMenuItems {
name: string;
level: number;
id: number;
pid: number;
children?: any[];
}
const TreeSettings = (data: menuItems[]) => {
return (
<>
{data.map((t) => {
return <div>{t.name}</div>;
})}
</>
);
};
The problem in Settings.tsx at <TreeSettings data={data} />; on data I get
(property) data: menuItems[]
Type '{ data: menuItems[]; }' is not assignable to type 'IntrinsicAttributes & menuItems[]'.
Property 'data' does not exist on type 'IntrinsicAttributes & menuItems[]'.ts(2322)
How do I pass the data in the prop with types ?
CodePudding user response:
U cant use interface as type parameter, but u can use typeof IMenuItems like this:
const TreeSettings = (data:typeof
menuItems[]) => {
return (
<>
{data.map((t) => {
return <div>{t.name}</div>;
})}
</>
);
};
CodePudding user response:
Function components are defined like so in Typescript:
import type { FC } from "react";
...
const TreeSettings: FC<{data: menuItems[]}> = ({data}) => {
...
}
FC
stands for Function Component. It is a generic type that allows you to define the type of props
, in this case {data: menuItems[]}
. You can then destructure the props, in this case: ({data})
, and the correct type will be inferred.
Fixed sandbox: https://codesandbox.io/s/data-is-not-a-function-forked-spp0xn?file=/src/TreeSettings.tsx
In your case you were not destructuring the props
object. Instead you declared the entire props object to have type menuItems[]
which is incorrect.
This line:
<TreeSettings data={data} />;
is equivalent to
TreeSettings({data: data})
This passes an object with a data
property to the Function Component.
It does not pass the array as the parameter.