Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types): add undefined initial value to Atom definition #2668

Merged
merged 3 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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