Skip to content
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
22 changes: 13 additions & 9 deletions crates/loro-wasm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,8 @@ export class Awareness<T extends Value = Value> {
* store2.apply(encoded);
* ```
*/
export class EphemeralStore<T extends Value = Value> {
inner: EphemeralStoreWasm<T>;
export class EphemeralStore<T extends Record<string, Value> = Record<string, Value>> {
inner: EphemeralStoreWasm;
private timer: number | undefined;
private timeout: number;
constructor(timeout: number = 30000) {
Expand All @@ -263,21 +263,25 @@ export class EphemeralStore<T extends Value = Value> {
this.startTimerIfNotEmpty();
}

set(key: string, value: T) {
this.inner.set(key, value);
set<K extends keyof T>(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<K extends keyof T>(key: K) {
this.inner.delete(key as string);
}

getAllStates(): Record<string, T> {
get<K extends keyof T>(key: K): T[K] | undefined {
return this.inner.get(key as string);
}

getAllStates(): Partial<T> {
return this.inner.getAllStates();
}

encode(key: string): Uint8Array {
return this.inner.encode(key);
encode<K extends keyof T>(key: K): Uint8Array {
return this.inner.encode(key as string);
}

encodeAll(): Uint8Array {
Expand Down
25 changes: 25 additions & 0 deletions crates/loro-wasm/tests/ephemeral.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down