From 5cf5a1620d9a97382d386c277265d9dd051fe484 Mon Sep 17 00:00:00 2001 From: Tycho Date: Wed, 14 Aug 2024 15:11:10 +0800 Subject: [PATCH] fix(types/computed): ensure type safety for `WritableComputedRef` (#11608) --- packages-private/dts-test/ref.test-d.ts | 8 ++++++++ packages/reactivity/src/computed.ts | 15 ++++++++++----- packages/runtime-core/src/apiComputed.ts | 2 +- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/packages-private/dts-test/ref.test-d.ts b/packages-private/dts-test/ref.test-d.ts index 89dbeacb382..929e3d1a1ab 100644 --- a/packages-private/dts-test/ref.test-d.ts +++ b/packages-private/dts-test/ref.test-d.ts @@ -209,6 +209,14 @@ describe('allow computed getter and setter types to be unrelated', () => { expectType(c.value) }) +describe('Type safety for `WritableComputedRef` and `ComputedRef`', () => { + // @ts-expect-error + const writableComputed: WritableComputedRef = computed(() => '') + // should allow + const immutableComputed: ComputedRef = writableComputed + expectType>(immutableComputed) +}) + // shallowRef type Status = 'initial' | 'ready' | 'invalidating' const shallowStatus = shallowRef('initial') diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index bb9f9e02fcb..aa5d2079061 100644 --- a/packages/reactivity/src/computed.ts +++ b/packages/reactivity/src/computed.ts @@ -14,19 +14,24 @@ import { Dep, globalVersion } from './dep' import { ReactiveFlags, TrackOpTypes } from './constants' declare const ComputedRefSymbol: unique symbol +declare const WritableComputedRefSymbol: unique symbol -export interface ComputedRef extends WritableComputedRef { - readonly value: T +interface BaseComputedRef extends Ref { [ComputedRefSymbol]: true -} - -export interface WritableComputedRef extends Ref { /** * @deprecated computed no longer uses effect */ effect: ComputedRefImpl } +export interface ComputedRef extends BaseComputedRef { + readonly value: T +} + +export interface WritableComputedRef extends BaseComputedRef { + [WritableComputedRefSymbol]: true +} + export type ComputedGetter = (oldValue?: T) => T export type ComputedSetter = (newValue: T) => void diff --git a/packages/runtime-core/src/apiComputed.ts b/packages/runtime-core/src/apiComputed.ts index a7d959dfaaa..2ebb2d4e63a 100644 --- a/packages/runtime-core/src/apiComputed.ts +++ b/packages/runtime-core/src/apiComputed.ts @@ -13,5 +13,5 @@ export const computed: typeof _computed = ( ;(c as unknown as ComputedRefImpl)._warnRecursive = true } } - return c + return c as any }