Skip to content

Commit 3b8f9ad

Browse files
LucasLefevreged-odoo
authored andcommitted
type computed.set
1 parent f0e9372 commit 3b8f9ad

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

src/runtime/reactivity/computations.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import { batched } from "../utils";
22

3-
export interface ReactiveValue<T> {
4-
(): T;
3+
export interface ReactiveValue<TRead, TWrite=TRead> {
4+
(): TRead;
55
/**
66
* Update the value of the reactive with a new value. If the new value is different
77
* from the previous values, all computations that depends on this reactive will
88
* be invalidated, and effects will rerun.
99
*/
10-
set(nextValue: any): void;
10+
set(nextValue: TWrite): void;
1111
}
1212

1313
export enum ComputationState {

src/runtime/reactivity/computed.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ import {
77
createComputation,
88
} from "./computations";
99

10-
interface ComputedOptions {
11-
set?(value: any): void;
10+
interface ComputedOptions<TWrite> {
11+
set?(value: TWrite): void;
1212
}
1313

14-
export function computed<T>(getter: () => T, options: ComputedOptions = {}): ReactiveValue<T> {
14+
export function computed<TRead, TWrite=TRead>(getter: () => TRead, options: ComputedOptions<TWrite> = {}): ReactiveValue<TRead, TWrite> {
1515
const computation = createComputation({
1616
compute: () => {
1717
onWriteAtom(computation);

tests/reactivity/computed.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,4 +386,26 @@ describe("writable computed", () => {
386386

387387
cleanupEffect();
388388
});
389+
390+
test("compute can read and write different types", () => {
391+
const value = signal(4);
392+
const binary = computed(() => value().toString(2), {
393+
set: (nextValue: string | number) => {
394+
if(typeof nextValue === "number") {
395+
value.set(nextValue)
396+
} else {
397+
value.set(parseInt(nextValue, 2))
398+
}
399+
}
400+
})
401+
expect(binary()).toBe("100")
402+
403+
// can set a string
404+
binary.set("110")
405+
expect(value()).toBe(6)
406+
407+
// can also set a number
408+
binary.set(7)
409+
expect(value()).toBe(7)
410+
})
389411
});

0 commit comments

Comments
 (0)