Reputation: 2588
I am trying to run a reduce on an array of objects but TypeScript says:
`Argument of type 'string' is not assignable to parameter of type 'never'`
I know it defaults to never because I need to declare the array of strings but I do not know where should I do it here
store.ts
// I have this data on a context provider
const data = [{
Name: 'Peter',
Dept: 'Finance'
},{
Name: 'Jane',
Dept: 'HR'
},{
Name: 'Tom',
Dept: 'HR'
}]
import { useMainContext } from './store'
function App = () {
const { data } = useMainContext()
const [departments, setDepartments] = useState<string[] | undefined>([])
type Props = {
Name: string,
Dept: string
}
// I dont now where to include the props
useEffect(() => {
const depts = data.reduce((acc, current) => {
if (!acc.includes(current.Dept))
acc.push(current.Dept)
return acc
}, [])
setDepartments(depts)
}, [])
...
}
Upvotes: 0
Views: 1165
Reputation: 512
Just use Type Assertion for your initial value for .reduce()
const depts = data.reduce((acc, current) => {
if (!acc.includes(current.Dept))
acc.push(current.Dept)
return acc
}, [] as string[]) //Added as string[]
Upvotes: 2