diff --git a/crates/loro-wasm/index.ts b/crates/loro-wasm/index.ts index b3858acda..0b54c2500 100644 --- a/crates/loro-wasm/index.ts +++ b/crates/loro-wasm/index.ts @@ -249,8 +249,8 @@ export class Awareness { * store2.apply(encoded); * ``` */ -export class EphemeralStore { - inner: EphemeralStoreWasm; +export class EphemeralStore = Record> { + inner: EphemeralStoreWasm; private timer: number | undefined; private timeout: number; constructor(timeout: number = 30000) { @@ -263,21 +263,25 @@ export class EphemeralStore { this.startTimerIfNotEmpty(); } - set(key: string, value: T) { - this.inner.set(key, value); + set(key: K, value: T[K]) { + this.inner.set(key as string, value); this.startTimerIfNotEmpty(); } - get(key: string): T | undefined { - return this.inner.get(key); + delete(key: K) { + this.inner.delete(key as string); } - getAllStates(): Record { + get(key: K): T[K] | undefined { + return this.inner.get(key as string); + } + + getAllStates(): Partial { return this.inner.getAllStates(); } - encode(key: string): Uint8Array { - return this.inner.encode(key); + encode(key: K): Uint8Array { + return this.inner.encode(key as string); } encodeAll(): Uint8Array { diff --git a/crates/loro-wasm/tests/ephemeral.test.ts b/crates/loro-wasm/tests/ephemeral.test.ts index c7835116a..dd39fa6fa 100644 --- a/crates/loro-wasm/tests/ephemeral.test.ts +++ b/crates/loro-wasm/tests/ephemeral.test.ts @@ -116,6 +116,31 @@ describe("EphemeralStore", () => { }); }); + it("generic type", () => { + // Define a type to test type inference + const store = new EphemeralStore<{ foo: string, bar: number }>(10); + // This should compile correctly + store.set("foo", "bar"); + store.set("bar", 1); + + // Verify runtime values are correct + expect(store.get("foo")).toBe("bar"); + expect(store.get("bar")).toBe(1); + + // Type inference for get should work too + const foo: string | undefined = store.get("foo"); + const bar: number | undefined = store.get("bar"); + expect(foo).toBe("bar"); + expect(bar).toBe(1); + + // @ts-expect-error - This should fail type checking as "foo" expects string + store.set("foo", 123); + // @ts-expect-error - This should fail type checking as "bar" expects number + store.set("bar", "string"); + // @ts-expect-error - This should fail type checking as "baz" is not in the type + store.set("baz", "value"); + }); + it("subscribe", () => { const store = new EphemeralStore(10); let callTimes = 0;