Skip to content

Commit

Permalink
fix: add undefined initial value to primitive Atom definition (#2668)
Browse files Browse the repository at this point in the history
Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
  • Loading branch information
rtritto and dai-shi authored Jul 23, 2024
1 parent 98e23c9 commit 2fbcc4d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/vanilla/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,17 @@ export function atom<Value, Args extends unknown[], Result>(
write: Write<Args, Result>,
): WritableAtom<Value, Args, Result> & WithInitialValue<Value>

// primitive atom without initial value
export function atom<Value>(): PrimitiveAtom<Value | undefined> &
WithInitialValue<Value | undefined>

// primitive atom
export function atom<Value>(
initialValue: Value,
): PrimitiveAtom<Value> & WithInitialValue<Value>

export function atom<Value, Args extends unknown[], Result>(
read: Value | Read<Value, SetAtom<Args, Result>>,
read?: Value | Read<Value, SetAtom<Args, Result>>,
write?: Write<Args, Result>,
) {
const key = `atom${++keyCount}`
Expand All @@ -97,7 +101,7 @@ export function atom<Value, Args extends unknown[], Result>(
? key + ':' + this.debugLabel
: key
},
} as WritableAtom<Value, Args, Result> & { init?: Value }
} as WritableAtom<Value, Args, Result> & { init?: Value | undefined }
if (typeof read === 'function') {
config.read = read as Read<Value, SetAtom<Args, Result>>
} else {
Expand Down
10 changes: 10 additions & 0 deletions tests/vanilla/types.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expectType } from 'ts-expect'
import type { TypeOf } from 'ts-expect'
import { it } from 'vitest'
import { atom } from 'jotai/vanilla'
import type {
Expand All @@ -15,6 +16,15 @@ it('atom() should return the correct types', () => {
// primitive atom
const primitiveAtom = atom(0)
expectType<PrimitiveAtom<number>>(primitiveAtom)
expectType<TypeOf<PrimitiveAtom<number>, typeof primitiveAtom>>(true)
expectType<TypeOf<PrimitiveAtom<number | undefined>, typeof primitiveAtom>>(
false,
)

// primitive atom without initial value
const primitiveWithoutInitialAtom = atom<number | undefined>()
expectType<PrimitiveAtom<number | undefined>>(primitiveWithoutInitialAtom)
expectType<PrimitiveAtom<undefined>>(atom())

// read-only derived atom
const readonlyDerivedAtom = atom((get) => get(primitiveAtom) * 2)
Expand Down

0 comments on commit 2fbcc4d

Please sign in to comment.