Skip to content

Commit 8e726ed

Browse files
Add typing for effect cleanup (#249)
* pass along hook effect cleanup * add effect cleanup types * Add changeset --------- Co-authored-by: Jovi De Croock <[email protected]>
1 parent b10bfc1 commit 8e726ed

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

.changeset/polite-ghosts-yell.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@preact/signals-core": patch
3+
---
4+
5+
Add typing for effect cleanup

packages/core/src/index.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -655,21 +655,21 @@ function endEffect(this: Effect, prevContext?: Computed | Effect) {
655655
}
656656

657657
declare class Effect {
658-
_compute?: () => unknown;
659-
_cleanup?: unknown;
658+
_compute?: () => void | (() => void);
659+
_cleanup?: () => void;
660660
_sources?: Node;
661661
_nextBatchedEffect?: Effect;
662662
_flags: number;
663663

664-
constructor(compute: () => void);
664+
constructor(compute: () => void | (() => void));
665665

666666
_callback(): void;
667667
_start(): () => void;
668668
_notify(): void;
669669
_dispose(): void;
670670
}
671671

672-
function Effect(this: Effect, compute: () => void) {
672+
function Effect(this: Effect, compute: () => void | (() => void)) {
673673
this._compute = compute;
674674
this._cleanup = undefined;
675675
this._sources = undefined;
@@ -680,8 +680,12 @@ function Effect(this: Effect, compute: () => void) {
680680
Effect.prototype._callback = function () {
681681
const finish = this._start();
682682
try {
683-
if (!(this._flags & DISPOSED) && this._compute !== undefined) {
684-
this._cleanup = this._compute();
683+
if (this._flags & DISPOSED) return;
684+
if (this._compute === undefined) return;
685+
686+
const cleanup = this._compute();
687+
if (typeof cleanup === "function") {
688+
this._cleanup = cleanup;
685689
}
686690
} finally {
687691
finish();
@@ -719,7 +723,7 @@ Effect.prototype._dispose = function () {
719723
}
720724
};
721725

722-
function effect(compute: () => unknown): () => void {
726+
function effect(compute: () => void | (() => void)): () => void {
723727
const effect = new Effect(compute);
724728
try {
725729
effect._callback();

0 commit comments

Comments
 (0)