Issue
I am trying to understand what this TypeScript error is telling me and how to resolve it.
Type '(status: string) => { text: string; onClick: () => void; }[] | undefined' is not assignable to type '{ text: string; onClick: () => void; }[]'
I have a header component which accepts an array of objects.
I can pass the array in as follows with no issues.
menuItems={[
{ text: 'Save', onClick: () => console.log('test1') },
{
text: 'Submit Referral Request',
onClick: () => console.log('test2'),
},
]}
/>
Now what I want to do is extract the array and replace it with a function call that will build an array.
function renderActionMenuItems(status: string) {
if (status === 'new') {
return new Array(
{ text: 'Save', onClick: () => console.log('test1') },
{
text: 'Submit Referral Request',
onClick: () => console.log('test2'),
}
)
}
}
<ActionBar
menuItems={renderActionMenuItems}
/>
However the above code gives me an error when running the app.
ActionBar.tsx:83 Uncaught TypeError: t2.map is not a function
and the following error in my IDE
Type '(status: string) => { text: string; onClick: () => void; }[] | undefined' is not assignable to type '{ text: string; onClick: () => void; }[]'.ts(2322)
index.d.ts(93, 5): The expected type comes from property 'menuItems' which is declared here on type 'IntrinsicAttributes & HeaderProps'
Solution
The issue is you need to return an empty array if status is not "new":
function renderActionMenuItems(status: string) {
if (status === 'new') {
return new Array(
{ text: 'Save', onClick: () => console.log('test1') },
{
text: 'Submit Referral Request',
onClick: () => console.log('test2'),
}
)
}
return []; // <-- Would have returned undefined without explicitly returning.
}
Consider typing your array elements and having a return type defined for the function. Explicitly defining return types will help you avoid issues like this in the future.
interface MenuType {
text: string;
onClick: () => void;
}
/** This would've shown an error in the IDE: */
function renderActionMenuItems(status: string): MenuType[] { // <-- Return type
/* ... */
}
Answered By - Daniel Gimenez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.