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

feat: typed storage interface #509

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

wzc520pyfm
Copy link

Refer: #508

We can improve the ts type as follows:

type TestObjType = {
  a: number;
  b: boolean;
};
type MyStorage = {
  foo: string;
  baz: TestObjType;
};
const storage = createStorage<MyStorage>();
await storage.getItem("foo"); // => <string>
await storage.getItem("baz"); // => <TestObjType>
storage.setItem("foo", "val"); // Check ok
storage.setItem("foo", 123); // TS error

and get hints as you type:
image

a: number;
b: boolean;
};
type MyStorage = {
Copy link
Member

@pi0 pi0 Nov 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For future expansion of first generic, i prefer that we namespace it like Storage<{ data: { /* KV types */ } }>

(also can you please add ts example to a new section in the end of page? 🙏🏼

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, I don't understand, could you explain it more detail? I guess you mean to adjust the definition of getItem like:

type NsObject = {
  data: object
  [key: string]: any
}
export interface Storage<T extends StorageValue = StorageValue> {
  // ...
  getItem<U extends Extract<T, NsObject>, K extends keyof U["data"]>(
     key: K, ops?: TransactionOptions
  ): Promise<U["data"][K] | null>;
  getItem<U extends T>(key: string, opts?: TransactionOptions ): Promise<U | null>;
}
image

Copy link
Member

@pi0 pi0 Nov 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes! (ideas welcome for data key name. mainly namespacing is important)

@pi0 pi0 changed the title type(storage): enhance ts type for get/set/has/del feat: typed storage interface Nov 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants