Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
type validation for createStore
Browse files Browse the repository at this point in the history
omarluq committed Nov 24, 2023
1 parent 9ee65cf commit b39dcfc
Showing 2 changed files with 10 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/createStore.ts
Original file line number Diff line number Diff line change
@@ -29,6 +29,7 @@

import { Store } from './store';
import type { StoreOptions } from './storeOptions';
import { typeMap } from './storeValuesTypeMap';

export function createStore<T>(options: StoreOptions<T>): Store<T> {
const { name, type, initialValue } = options;
@@ -39,5 +40,10 @@ export function createStore<T>(options: StoreOptions<T>): Store<T> {
}
const symbolName = Symbol(name);

const typeConstructor = typeMap[type.name];
if (typeof typeConstructor !== 'function') {
throw new Error(`Invalid type: ${type?.name}`);
}

return new Store<T>(symbolName, initialValue, type);
}
4 changes: 4 additions & 0 deletions test/createStore.test.ts
Original file line number Diff line number Diff line change
@@ -15,4 +15,8 @@ describe('createStore', () => {
expect(typeof store.get()).toBe('number');
expect(store.name.toString()).toBe('Symbol(testStore)');
});

it('should throw an error if an invalid type is provided', () => {
expect(() => createStore({ name: 'testStore', initialValue: 0, type: Set } as any)).toThrow('Invalid type: Set');
});
});

0 comments on commit b39dcfc

Please sign in to comment.