From 61d89416928ffc18f17334d280c707a59aeafbae Mon Sep 17 00:00:00 2001 From: Evan You Date: Fri, 8 Nov 2019 13:29:43 -0500 Subject: [PATCH] types(reactivity): ref type should not expose _isRef --- packages/reactivity/src/computed.ts | 2 +- packages/reactivity/src/ref.ts | 24 +++++++++++++++++------- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index c80297bb5..2788f8901 100644 --- a/packages/reactivity/src/computed.ts +++ b/packages/reactivity/src/computed.ts @@ -69,7 +69,7 @@ export function computed( set value(newValue: T) { setter(newValue) } - } + } as any } function trackChildRun(childRunner: ReactiveEffect) { diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 19c042a0f..b6c7835c4 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -5,14 +5,28 @@ import { reactive, isReactive } from './reactive' import { ComputedRef } from './computed' import { CollectionTypes } from './collectionHandlers' +const isRefSymbol = Symbol() + export interface Ref { - _isRef: true + // This field is necessary to allow TS to differentiate a Ref from a plain + // object that happens to have a "value" field. + // However, checking a symbol on an arbitrary object is much slower than + // checking a plain property, so we use a _isRef plain property for isRef() + // check in the actual implementation. + // The reason for not just declaring _isRef in the interface is because we + // don't want this internal field to leak into userland autocompletion - + // a private symbol, on the other hand, achieves just that. + [isRefSymbol]: true value: UnwrapRef } const convert = (val: T): T => isObject(val) ? reactive(val) : val +export function isRef(r: any): r is Ref { + return r ? r._isRef === true : false +} + export function ref(raw: T): T export function ref(raw: T): Ref export function ref(): Ref @@ -37,11 +51,7 @@ export function ref(raw?: unknown) { ) } } - return r as Ref -} - -export function isRef(r: any): r is Ref { - return r ? r._isRef === true : false + return r } export function toRefs( @@ -69,7 +79,7 @@ function toProxyRef( set value(newVal) { object[key] = newVal } - } + } as any } type UnwrapArray = { [P in keyof T]: UnwrapRef }