diff --git a/src/vanilla/atom.ts b/src/vanilla/atom.ts index 27795d4f06..d0907329ea 100644 --- a/src/vanilla/atom.ts +++ b/src/vanilla/atom.ts @@ -81,13 +81,17 @@ export function atom( write: Write, ): WritableAtom & WithInitialValue +// primitive atom without initial value +export function atom(): PrimitiveAtom & + WithInitialValue + // primitive atom export function atom( initialValue: Value, ): PrimitiveAtom & WithInitialValue export function atom( - read: Value | Read>, + read?: Value | Read>, write?: Write, ) { const key = `atom${++keyCount}` @@ -97,7 +101,7 @@ export function atom( ? key + ':' + this.debugLabel : key }, - } as WritableAtom & { init?: Value } + } as WritableAtom & { init?: Value | undefined } if (typeof read === 'function') { config.read = read as Read> } else { diff --git a/tests/vanilla/types.test.tsx b/tests/vanilla/types.test.tsx index e0744b887b..3c89725bc7 100644 --- a/tests/vanilla/types.test.tsx +++ b/tests/vanilla/types.test.tsx @@ -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 { @@ -15,6 +16,15 @@ it('atom() should return the correct types', () => { // primitive atom const primitiveAtom = atom(0) expectType>(primitiveAtom) + expectType, typeof primitiveAtom>>(true) + expectType, typeof primitiveAtom>>( + false, + ) + + // primitive atom without initial value + const primitiveWithoutInitialAtom = atom() + expectType>(primitiveWithoutInitialAtom) + expectType>(atom()) // read-only derived atom const readonlyDerivedAtom = atom((get) => get(primitiveAtom) * 2)