Skip to content

Commit f44bdb8

Browse files
committed
fix: Add another defineItem signature when init function is passed
#1601 adjusted the typing of `defineItem` to examine whether `defaultValue` or `fallback` were passed, and only then, remove the `null` from the possible returned value. However, it did not accommodate the case where an `init` function is passed to prevent a `null` return, which was previously allowed. Add a new type signature for this case, and add some tests for type expectations to catch the issue.
1 parent bb67910 commit f44bdb8

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

packages/storage/src/__tests__/index.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,6 +1315,18 @@ describe('Storage Utils', () => {
13151315
});
13161316
expectTypeOf(item).toEqualTypeOf<WxtStorageItem<number | null, {}>>();
13171317
});
1318+
1319+
it('should define a non-null value when options are passed with a non-null init function', () => {
1320+
const item = storage.defineItem(`local:test`, {
1321+
init: () => 123,
1322+
});
1323+
expectTypeOf(item).toEqualTypeOf<WxtStorageItem<number, {}>>();
1324+
1325+
const item2 = storage.defineItem(`local:test`, {
1326+
init: () => Promise.resolve(123),
1327+
});
1328+
expectTypeOf(item2).toEqualTypeOf<WxtStorageItem<number, {}>>();
1329+
});
13181330
});
13191331
});
13201332

packages/storage/src/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,12 @@ export interface WxtStorage {
749749
key: StorageItemKey,
750750
options: WxtStorageItemOptions<TValue> & { defaultValue: TValue },
751751
): WxtStorageItem<TValue, TMetadata>;
752+
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(
753+
key: StorageItemKey,
754+
options: WxtStorageItemOptions<TValue> & {
755+
init: () => TValue | Promise<TValue>;
756+
},
757+
): WxtStorageItem<TValue, TMetadata>;
752758
defineItem<TValue, TMetadata extends Record<string, unknown> = {}>(
753759
key: StorageItemKey,
754760
options: WxtStorageItemOptions<TValue>,

0 commit comments

Comments
 (0)