deno.land / x / jotai@v1.8.4 / docs / guides / typescript.mdx

typescript.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
---title: TypeScriptdescription: How to use Jotai with TypeScriptnav: 3.01---
## Version requirement
Jotai uses TypeScript 3.8+ syntax. Upgrade your TypeScript version if you're on 3.7.5 or lower.
Jotai relies heavily on type inferences and requires `strictNullChecks` to be enabled. Consider adding `"strict": true` in your tsconfig.json.[#550](https://github.com/pmndrs/jotai/issues/550)[#802](https://github.com/pmndrs/jotai/issues/802)[#838](https://github.com/pmndrs/jotai/issues/838)
## Notes
### Primitive atoms are basically type inferred
```jsconst numAtom = atom(0) // primitive number atomconst strAtom = atom('') // primitive string atom```
### Primitive atoms can be explicitly typed
```tsconst numAtom = atom<number>(0)const numAtom = atom<number | null>(0)const arrAtom = atom<string[]>([])```
### Derived atoms are also type inferred and explicitly typed
```tsconst asyncStrAtom = atom(async () => 'foo')const writeOnlyAtom = atom(null, (_get, set, str: string) => set(fooAtom, str))const readWriteAtom = atom<string, number>( (get) => get(strAtom), (_get, set, num) => set(strAtom, String(num)))```
### useAtom is typed based on atom types
```jsconst [num, setNum] = useAtom(primitiveNumAtom)const [num] = useAtom(readOnlyNumAtom)const [, setNum] = useAtom(writeOnlyNumAtom)```
jotai

Version Info

Tagged at
a year ago