ERROR in Cannot find name and implicity has any type - reactjs

The following error appears:
ERROR in src/components/Tasks.tsx:6:2
TS2552: Cannot find name 'Task'. Did you mean 'Tasks'?
4 | return(
5 | <>
> 6 | {Task.map((task) => (
| ^^^^
7 | <h3 key={task.id}>{task.text}</h3>
8 | )) }
9 |
ERROR in src/components/Tasks.tsx:6:12
TS7006: Parameter 'task' implicitly has an 'any' type.
4 | return(
5 | <>
> 6 | {Task.map((task) => (
| ^^^^
7 | <h3 key={task.id}>{task.text}</h3>
8 | )) }
9 |
Tasks.tsx code:
import PropTypes from 'prop-types'
const Tasks = () => {
return(
<>
{Task.map((task) => (
<h3 key={task.id}>{task.text}</h3>
)) }
</>
)
}
export default Tasks

error is caused because the TypeScript compiler cannot infer the type of the task parameter in the map function. You can fix this by explicitly defining the type of task using an interface or type.
import PropTypes from 'prop-types';
interface Task {
id: number;
text: string;
}
const tasks: Task[] = [
{ id: 1, text: 'Task 1' },
{ id: 2, text: 'Task 2' },
];
const Tasks = () => {
return (
<>
{tasks.map((task: Task) => (
<h3 key={task.id}>{task.text}</h3>
))}
</>
);
};
export default Tasks;
Also, define or import the Task variable and ensure that it is an array of objects with the properties id and text.

thank you for the answer, in the App.tsx is the following defined:
import { useState } from 'react'
import Header from './components/Header'
import Tasks from './components/Tasks'
const App = () => {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Audit mit Lieferanten Schäffler durchführen',
day: 'Feb 28th at 2:30 pm',
reminder: true,
},
{
id: 2,
text: 'Eskalation bei der Firma Balluff',
day: 'Feb 6th at 1:30 pm',
reminder: true,
},
{
id: 3,
text: 'Lieferantengespräch mit ADE durchführen',
day: 'Feb 5th at 2:30 pm',
reminder: false,
},
])
return (
<div className='container'>
<Header />
<Tasks />
</div>
)
}
export default App;

Related

Argument of Type 'undefined' is not assignable to type 'number | Date'

I'm trying to convert the data am getting from the dateRange variable, but I'm getting an error: Argument of type 'Date | undefined' is not assignable to the parameter of type 'number | Date'. Type 'undefined' is not assignable to type 'number | Date'.
What's wrong with my code?
//header file
import { useContextState } from '../context/context'
const Header = () => {
const { dateRange, setDateRange, setOpenDate, openDate } = useContextState()
return (
<span onClick={() => setOpenDate(true)} className="cursor-pointer">
{`${format(dateRange[0].startDate, "MM/dd/yyyy")} To ${format(dateRange[0].endDate, "MM/dd/yyyy")}`}
</span>
</nav>
)
}
export default Header
// context.tsx file
import { createContext, Dispatch, SetStateAction, useContext, useState } from "react";
import { addDays } from 'date-fns';
import { Range } from "react-date-range";
import { format } from "date-fns";
export interface Range {
startDate?: Date | undefined ;
endDate?: Date | undefined;
key?: string | undefined
}
interface IstateContext {
openDate: boolean
setOpenDate: Dispatch<SetStateAction<boolean>>
dateRange: Range[]
setDateRange: Dispatch<SetStateAction<Range[]>>
}
const initialState = {
openDate: false,
setOpenDate: () => false,
dateRange: [{
startDate: new Date(),
endDate: new Date(),
key: "selection",
}],
setDateRange: () => void{}
}
const StateContext = createContext<IstateContext>(initialState)
interface Childern {
children: React.ReactNode
}
export const ContextProvider: React.FC<Childern> = ({ children }) => {
const [openDate, setOpenDate] = useState<boolean>(false)
const [dateRange, setDateRange] = useState<Range[]>([
{
startDate: new Date(),
endDate: new Date(),
key: "selection",
},
])
return (
<StateContext.Provider value={{ dateRange, setDateRange, openDate, setOpenDate
}}>
{children}
</StateContext.Provider>
)
}
export const useContextState = () => useContext(StateContext)
If I understand the question correctly you want to pass dateRange.0.startDate/endDate to the format function however the values could be undefined and format does not accept undefined values.
Using type guards you can check against undefined values and handle that case.
const range = dateRange?.[0];
if (range?.startDate === undefined || range?.endDate === undefined) {
return <span>Invalid range!</span>
}
return (
<span onClick={() => setOpenDate(true)} className="cursor-pointer">
{`${format(range.startDate, "MM/dd/yyyy")} To ${format(range.endDate, "MM/dd/yyyy")}`}
</span>
)
Check 'Range'. You have imported from "react-date-range". And also you have made an interface that is unable to overite the property.
replace the third line with the code and confirm if it works. "added null check"
{${format(dateRange[0]?.startDate, "MM/dd/yyyy")} To ${format(dateRange[0]?.endDate, "MM/dd/yyyy")}}

How to type Mui v5 Chip color prop with value as object key

How can I type MUI Chip prop color if actual value comes from an object? At the moment I use any but it is not a good option. And one more question, is as keyof typeof CHIP_COLORS correct way for typing?
import { Chip, Stack } from "#mui/material";
const DATA = [
{
id: 2,
status: "success"
},
{
id: 3,
status: "finished"
},
{
id: 4,
status: "error"
}
];
const CHIP_COLORS = {
finished: "primary",
error: "error",
success: "success"
};
export default function App() {
return (
<Stack
sx={{gap: 5}}
>
{DATA.map(({ id, status }) => {
return (
<Chip
color={CHIP_COLORS[status as keyof typeof CHIP_COLORS] as any}
/>
);
})}
</Stack>
);
}
Codesandbox: https://codesandbox.io/s/festive-breeze-s4vpfk?file=/src/App.tsx
you can create custom types.
type eventType = "finished" | "success" | "error";
type colorType = "primary" | "error" | "success" | "default" | "secondary" | "info" | "warning" | undefined
your data type:
const DATA:{ id:number, status:eventType }[] = [
{
id: 2,
status: "success"
},
...
chip color type:
const CHIP_COLORS: { [key in eventType]: colorType } = {
finished: "primary",
error: "error",
success: "success"
};
component:
{DATA.map(({ id, status }) => {
return (
<>
<Chip color={CHIP_COLORS[status]} />
</>
);
})}

React - Property 'data' does not exist on type 'IntrinsicAttributes & InfoGridProps'

I have a demo here
I'm just trying to create a simple app where I pass data to a component and then display that data
So I have the data which is an array of objects I'm passing into the component DisplayData
import * as React from 'react';
import DisplayData from './DisplayData';
import './style.css';
export interface InfoGridProps {
title: string;
text: string;
}
const InfoGrid: InfoGridProps[] = [
{
title: 'Title 1',
text: 'Type 1 Type 1 Type 1 Type 1 Type 1',
},
{
title: 'Title 2',
text: 'Type 2 Type 2 Type 2 Type 2 Type 2 Type 2 Type 2 Type 2 ',
},
{
title: 'Title 3',
text: 'Type 3 Type 3 Type 3 Type 3 ',
},
];
export const App = () => {
return (
<div>
<DisplayData data={InfoGrid} />
</div>
);
};
export default App;
And then in the component I want to just loop through that data and displat it
import * as React from 'react';
import { FC } from 'react';
import './style.css';
export interface InfoGridProps {
title: string;
text: string;
}
export const DisplayData: FC<InfoGridProps[]> = (data) => {
return (
<div>
{data.map((item) => (
<div>
<h1>{item.title}</h1>
<p>{item.text}</p>
</div>
))}
</div>
);
};
export default DisplayData;
but here <DisplayData data={InfoGrid} /> it says
Property 'data' does not exist on type 'IntrinsicAttributes & InfoGridProps'.
How can I get this simple app to work and display the data passed in
The error is correct, in that you don't have data on your InfoGridProps type, which is what you've declared your DisplayData component to be.
I believe the correct way to type this is in DisplayData is to declare a type, and reference your data property as an array of that type:
import * as React from 'react'
import { FC } from 'react'
import './style.css'
export interface InfoGridProps {
data: InfoGridType[]
}
export type InfoGridType = {
title: string
text: string
}
export const DisplayData: FC<InfoGridProps[]> = (data) => {
return (
<div>
{data.map((item) => (
<div>
<h1>{item.title}</h1>
<p>{item.text}</p>
</div>
))}
</div>
)
}
export default DisplayData

Typescript ts2322: Type '{ id: number, name: string, paymentStatus: string }' is not assignable to type

Hi I just started learning Typescript with React and I need help, I couldn't figure out this error:
"Type '{ id: number, name: string, paymentStatus: string }' is not assignable to type 'InvoiceType'.
Object literal may only specify known properties but 'paymentStatus' does not exist in 'InvoiceType'. Did you mean to write 'payment_status'?"
It works fine if all components are in a single file as well as the interface, types and data but after separating them I got the error. I tried this payment_status?: 'paid' | 'pending'; inside the type InvoiceType but i get the same error.
Here's my interfaces
export interface IinvoiceListProps {
invoiceData: InvoiceDataType
}
export type InvoiceDataType = {
customer_name: string;
invoices: Array<InvoiceType>
}
export type InvoiceType = {
id: number;
name: string;
total: string;
payment_status?: PaymentStatus;
}
export type PaymentStatus = 'paid' | 'pending';
Here's my app
import React from 'react';
import InvoiceList from './components/InvoiceList';
import data from './data';
function App() {
return (
<div className="App">
<InvoiceList invoiceData={data} />
</div>
);
}
export default App;
Here's the InvoiceList
import { IinvoiceListProps } from "../interfaces_types";
const InvoiceList = ({invoiceData:{customer_name,invoices}}:IinvoiceListProps)=>{
return (
<div>
<h1>{customer_name}</h1>
<ul>
{
invoices.map((invoice)=>(
<li key={invoice.id}>
<h3>{invoice.name}</h3>
<p>{invoice.total} = {invoice?.payment_status}</p>
</li>
))
}
</ul>
</div>
)
}
export default InvoiceList;
And the data
import { InvoiceDataType } from "../interfaces_types";
const data: InvoiceDataType = {
customer_name:'Test',
invoices: [
{
id: 1,
name: 'Design Work',
total: '40.00'
},
{
id: 2,
name: 'SEO Work',
total: '50.00'
},
{
id: 3,
name: 'Dev Work',
total: '70.00',
paymentStatus: 'pending'
},
]
}
export default data;
Your interface has filed name is payment_status. But you are trying to assign paymentStatus. Change paymentStatus to payment_status in the data.
{
id: 3,
name: 'Dev Work',
total: '70.00',
payment_status: 'pending'
}

Component should be returning a JSX.Element, but says it is not returning a value at all

The component in question is this:
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => {
props.map((item, index) => {
return <a href={item.href} key={index}>{item.name}</a>
})
};
export default NavigationItems;
Which is generating this error:
ERROR in src/components/navigation/NavigationItems.tsx:1:66
TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.
> 1 | const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => {
| ^^^^^^^^^^^
2 | props.map((item, index) => {
3 | return <a href={item.href} key={index}>{item.name}</a>
4 | })
I've tried to do:
return props.map((item, index) => {
<a href={item.href} key={index}>{item.name}</a>
})
Which then results in:
ERROR in src/components/navigation/NavigationItems.tsx:2:3
TS2739: Type 'void[]' is missing the following properties from type 'ReactElement<any, any>': type, props, key
Also tried:
return props.map((item, index) => {
return <a href={item.href} key={index}>{item.name}</a>
})
Which results in:
ERROR in src/components/navigation/NavigationItems.tsx:2:3
TS2739: Type 'Element[]' is missing the following properties from type 'ReactElement<any, any>
So I'm not quite sure what is going on here.
Any suggestions?
The dataset:
{
"navbar": {
"navBrand": "My Name",
"navItems": [
{
"name": "Bio",
"href": "#bio"
},
{
"name": "Projects",
"href": "#projects"
},
{
"name": "Articles",
"href": "#articles"
},
{
"name": "Resume",
"href": "#resume"
},
{
"name": "Contact",
"href": "#contact"
}
]
}
}
The parent component:
// Bootstrap imports
import { Container, Navbar } from 'react-bootstrap';
// Component imports
import NavigationItems from './NavigationItems';
// Import data
import data from '../../data/data.json';
const Navigation = () => {
return (
<Navbar>
<Container>
<Navbar.Brand>{data.navbar.navBrand}</Navbar.Brand>
<NavigationItems {...data.navbar.navItems} />
</Container>
</Navbar>
);
};
export default Navigation;
Doing something like:
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => (
<>
props.map((item, index) => {
return <a href={item.href} key={index}>{item.name}</a>
})
</>
);
Results in:
ERROR in src/components/navigation/NavigationItems.tsx
Line 5:27: Parsing error: Unexpected token. Did you mean `{'>'}` or `>`?
webpack 5.65.0 compiled with 2 errors in 131 ms
ERROR in src/components/navigation/NavigationItems.tsx:5:28
TS1382: Unexpected token. Did you mean `{'>'}` or `>`?
3 | const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => (
4 | <>
> 5 | props.map((item, index) => {
| ^
6 | return <a href={item.href} key={index}>{item.name}</a>
7 | })
8 | </>
ERROR in src/components/navigation/NavigationItems.tsx:6:5
TS1109: Expression expected.
4 | <>
5 | props.map((item, index) => {
> 6 | return <a href={item.href} key={index}>{item.name}</a>
| ^^^^^^
7 | })
8 | </>
9 | );
ERROR in src/components/navigation/NavigationItems.tsx:6:21
TS2304: Cannot find name 'item'.
4 | <>
5 | props.map((item, index) => {
> 6 | return <a href={item.href} key={index}>{item.name}</a>
| ^^^^
7 | })
8 | </>
9 | );
ERROR in src/components/navigation/NavigationItems.tsx:6:37
TS2304: Cannot find name 'index'.
4 | <>
5 | props.map((item, index) => {
> 6 | return <a href={item.href} key={index}>{item.name}</a>
| ^^^^^
7 | })
8 | </>
9 | );
ERROR in src/components/navigation/NavigationItems.tsx:6:45
TS2304: Cannot find name 'item'.
4 | <>
5 | props.map((item, index) => {
> 6 | return <a href={item.href} key={index}>{item.name}</a>
| ^^^^
7 | })
8 | </>
9 | );
ERROR in src/components/navigation/NavigationItems.tsx:7:3
TS1381: Unexpected token. Did you mean `{'}'}` or `&rbrace;`?
5 | props.map((item, index) => {
6 | return <a href={item.href} key={index}>{item.name}</a>
> 7 | })
| ^
8 | </>
9 | );
10 |
This is what the props object looks like that is being passed in from <NavigationItems {...data.navbar.navItems}:
{0: {name: "Bio", href: "#bio"}, 1: {name: "Projects", href: "#projects"}, 2: {name: "Articles", href: "#articles"}, 3: {name: "Resume", href: "#resume"}, 4: {name: "Contact", href: "#contact"}}
Your first example isn't returning anything. When you enclose the body of an arrow function in curly braces e.g. const myFunc = () => { ...body } you have to explicitly put a return inside. What you want is to omit the curly braces.
However, that will still not work, because you'll be returning an array rather than an element. You can use a React fragment, such as:
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => (
<>
props.map((item, index) => {
return <a href={item.href} key={index}>{item.name}</a>
})
</>
);
I typed this on my phone so I hope that syntax is correct. But the <> indicates a fragment. You can read more here: https://reactjs.org/docs/fragments.html
Note that <>...</> is shorthand for <React.Fragment>...</React.Fragment>
I think you should return the map result.
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => {
// add return here
return props.map((item, index) => {
return <a href={item.href} key={index}>{item.name}</a>
})
};
export default NavigationItems;
or to simplify (maybe), you can write it like this
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element =>
props.map((item, index) => <a href={item.href} key={index}>{item.name}</a>)
I managed to get this working with the help of Derek's comment and Matt U's answer.
It not only needed to be in a React.Fragment (<></>), but inside of curly braces {}.
The parent component:
// Navigation.tsx
// Bootstrap imports
import { Container, Navbar } from 'react-bootstrap';
// Component imports
import NavigationItems from './NavigationItems';
// Import data
import data from '../../data/data.json';
const Navigation = () => {
return (
<Navbar>
<Container>
<Navbar.Brand>{data.navbar.navBrand}</Navbar.Brand>
<NavigationItems {...data.navbar.navItems} />
</Container>
</Navbar>
);
};
export default Navigation;
The child component:
const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => (
<>
{
Object.entries(props).map((item, index) => {
return <a href={item[1].href} key={index}>{item[1].name}</a>
})
}
</>
);
export default NavigationItems;
This is the original data format:
{
"navbar": {
"navBrand": "My Name",
"navItems": [
{
"name": "Bio",
"href": "#bio"
},
{
"name": "Projects",
"href": "#projects"
},
{
"name": "Articles",
"href": "#articles"
},
{
"name": "Resume",
"href": "#resume"
},
{
"name": "Contact",
"href": "#contact"
}
]
}
}
But what is actually being passed in to the props with <NavigationItems {...data.navbar.navItems} /> is:
{0: {name: "Bio", href: "#bio"}, 1: {name: "Projects", href: "#projects"}, 2: {name: "Articles", href: "#articles"}, 3: {name: "Resume", href: "#resume"}, 4: {name: "Contact", href: "#contact"}}
So needed to use Object.entries(props).map().

Resources