Skip to content

Commit 3b9c143

Browse files
committed
feat(computed): add isComputed helper
1 parent 9d5dd2d commit 3b9c143

File tree

4 files changed

+30
-4
lines changed

4 files changed

+30
-4
lines changed

packages/reactivity/__tests__/deferredComputed.spec.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { computed, deferredComputed, effect, ref } from '../src'
1+
import {
2+
computed,
3+
deferredComputed,
4+
effect,
5+
isComputed,
6+
reactive,
7+
ref,
8+
toRaw
9+
} from '../src'
210

311
describe('deferred computed', () => {
412
const tick = Promise.resolve()
@@ -182,4 +190,13 @@ describe('deferred computed', () => {
182190
await tick
183191
expect(c1Spy).toHaveBeenCalledTimes(1)
184192
})
193+
194+
it('isComputed', () => {
195+
expect(isComputed(computed(() => 1))).toBe(true)
196+
expect(isComputed(deferredComputed(() => 1))).toBe(true)
197+
expect(isComputed(ref(1))).toBe(false)
198+
expect(isComputed(reactive({}))).toBe(false)
199+
expect(isComputed(reactive({ c: computed(() => 1) }).c)).toBe(false)
200+
expect(isComputed(toRaw(reactive({ c: computed(() => 1) })).c)).toBe(true)
201+
})
185202
})

packages/reactivity/src/computed.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export interface WritableComputedOptions<T> {
2020
set: ComputedSetter<T>
2121
}
2222

23-
class ComputedRefImpl<T> {
23+
export class ComputedRefImpl<T> {
2424
public dep?: Dep = undefined
2525

2626
private _value!: T

packages/reactivity/src/deferredComputed.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Dep } from './dep'
22
import { ReactiveEffect } from './effect'
3-
import { ComputedGetter, ComputedRef } from './computed'
3+
import { ComputedGetter, ComputedRef, ComputedRefImpl } from './computed'
44
import { ReactiveFlags, toRaw } from './reactive'
55
import { trackRefValue, triggerRefValue } from './ref'
66

@@ -24,6 +24,15 @@ const flush = () => {
2424
queued = false
2525
}
2626

27+
export function isComputed<T>(
28+
value: ComputedRef<T> | unknown
29+
): value is ComputedRef<T>
30+
export function isComputed(value: any): value is ComputedRef {
31+
return (
32+
value instanceof ComputedRefImpl || value instanceof DeferredComputedRefImpl
33+
)
34+
}
35+
2736
class DeferredComputedRefImpl<T> {
2837
public dep?: Dep = undefined
2938

packages/reactivity/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export {
3636
ComputedGetter,
3737
ComputedSetter
3838
} from './computed'
39-
export { deferredComputed } from './deferredComputed'
39+
export { deferredComputed, isComputed } from './deferredComputed'
4040
export {
4141
effect,
4242
stop,

0 commit comments

Comments
 (0)