When using ReactN with TypeScript, I got an error message “Argument of type ‘“a”’ is not assignable to parameter of type ‘never’. I fixed it by feeling without reading the manual, but it was not actually fixed, so I wrote down the correct way to fix it.
When I added a type specification to useGlobal, the compile error disappeared and I thought that was all right, but the type was wrong and the problem occurred later. ts
How to fix it right https://github.com/CharlesStover/reactn/blob/master/README.md#typescript-support ts
the reason why a: string | number
ts
ts
This is caused by the fact that when one type is specified for generics, which takes two type arguments, the other type is changed. If no type argument is specified, the type Key is inferred from the argument, which is a literal type of string. On the other hand, if the type is passed to Dict, Key becomes the keyof Dict. In this case, it becomes the union type of all keys. ts
G[P]
of StateTuple[0]
, since P is the union type of all keys
ts
export type StateTuple<G extends {}, P extends keyof G> = [
G[P],
Setter<G, P>,
];
This page is auto-translated from /nishio/ReactN+TypeScript using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I’m very happy to spread my thought to non-Japanese readers.