From 7f8cceb79d86179b494b367ea6698ed2234ca9cd Mon Sep 17 00:00:00 2001 From: rtritto Date: Tue, 23 Jul 2024 10:30:49 +0200 Subject: [PATCH] fix: add undefined initial value to primitive Atom definition --- src/vanilla/atom.ts | 8 ++++++-- tests/vanilla/types.test.tsx | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/vanilla/atom.ts b/src/vanilla/atom.ts index b2cfcba268..c4d5b513e5 100644 --- a/src/vanilla/atom.ts +++ b/src/vanilla/atom.ts @@ -81,19 +81,23 @@ 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}` const config = { toString: () => 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)