dragonmnl
dragonmnl

Reputation: 15558

How to define a generic array type in React hooks-Typescript?

Hook:

const t = Array<number>
const [list, setList]: [t, ListFunction<t> ] = useState(null)

Type:

export type ListFunction<r> = Array<r[]> 

Gives:

Type '[any, Dispatch]' is not assignable to type '[t ListFunction]'. Type 'Dispatch' is missing the following properties from type 't[]': pop, push, concat, join, and 27 more.ts(2322)

This works instead:

export type ListFunction = Array<any[]> 

Upvotes: 0

Views: 1447

Answers (1)

Ori Drori
Ori Drori

Reputation: 192422

The type of setX (setList) in this case is not Array<r[]>. Just set the type of the useState() to be <number[]>), and let it infer the types of the value, and the set function:

const [list, setList] = useState<number[] | null>(null);

I would also initialize with an empty array, and avoid the need to check if the value list is not null.

const [list, setList] = useState<number[]>([]);

Upvotes: 1

Related Questions