I am creating custom hook useArray
in react with typescript which perform methods of array like push, update, remove etc. In js it is working fine but in ts there are some errors. below are the code from files:
useArray.ts
import { useState } from "react";
export default function useArray<T extends Element>(defaultValue: T[]): {
array: T[],
set: React.Dispatch<SetStateAction<T[]>>,
push: (elemet: T) => void,
remove: (index: T) => void,
filter: (callback: (n: T) => boolean) => void,
update: (index: number, newElement: T) => void,
clear: () => void
} {
const [array, setArray] = useState(defaultValue);
function push(element: T) {
setArray((a) => [...a, element]);
}
function filter(callback: (n: T) => boolean) {
setArray((a) => a.filter(callback));
}
function update(index: number, newElement: T) {
setArray((a) => [
...a.slice(0, index),
newElement,
...a.slice(index + 1, a.length),
]);
}
function remove(index: number) {
setArray((a) => [...a.slice(0, index), ...a.slice(index + 1, a.length)]);
}
function clear() {
setArray([]);
}
return { array, set: setArray, push, filter, update, remove, clear };
}
App.tsx
import ArrayComp from "./components/ArrayComp";
function App() {
return (
<div className="App">
<ArrayComp />
</div>
);
}
export default App;
ArrayComp.tsx
import useArray from "./useArray";
function ArrayComp() {
const { array, set, push, remove, filter, update, clear } = useArray([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
]);
return (
<div>
<h1>Updated array: </h1>
<div> {array.join(", ")} </div>
<button onClick={() => set([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 34, 21])}>
set to[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 34, 21]
</button>
<button onClick={() => push(5)}> Add 5 </button>
<button onClick={() => update(3, 5)}> update 5 at index 3 </button>
<button onClick={() => filter((n) => n < 10)}>
filter numbers less than 10
</button>
<button onClick={() => remove(3)}> Remove forth Element </button>
<button onClick={clear}> Empty array </button>
</div>
);
}
export default ArrayComp;
I am getting this error:
"Type 'number' is not assignable to type 'Element'"
at multiple places. I want that array elements can be of any possible type but I don't want to make its type as any. any suggestions will be appreciated.
solution : With using generics it is working fine. useArray.ts :