]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(types/computed): ensure type safety for `WritableComputedRef` (#11608)
authorTycho <jh.leong@outlook.com>
Wed, 14 Aug 2024 07:11:10 +0000 (15:11 +0800)
committerGitHub <noreply@github.com>
Wed, 14 Aug 2024 07:11:10 +0000 (15:11 +0800)
packages-private/dts-test/ref.test-d.ts
packages/reactivity/src/computed.ts
packages/runtime-core/src/apiComputed.ts

index 89dbeacb38276fd2bfa952c9d63572160e684911..929e3d1a1ab3f94fb208e6d804822c90bd50d181 100644 (file)
@@ -209,6 +209,14 @@ describe('allow computed getter and setter types to be unrelated', () => {
   expectType<string>(c.value)
 })
 
+describe('Type safety for `WritableComputedRef` and `ComputedRef`', () => {
+  // @ts-expect-error
+  const writableComputed: WritableComputedRef<string> = computed(() => '')
+  // should allow
+  const immutableComputed: ComputedRef<string> = writableComputed
+  expectType<ComputedRef<string>>(immutableComputed)
+})
+
 // shallowRef
 type Status = 'initial' | 'ready' | 'invalidating'
 const shallowStatus = shallowRef<Status>('initial')
index bb9f9e02fcb0c6d6919614b4077b7c1e11a5869f..aa5d2079061f8d36caed72484ab628bd641c7c44 100644 (file)
@@ -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<T = any> extends WritableComputedRef<T> {
-  readonly value: T
+interface BaseComputedRef<T, S = T> extends Ref<T, S> {
   [ComputedRefSymbol]: true
-}
-
-export interface WritableComputedRef<T, S = T> extends Ref<T, S> {
   /**
    * @deprecated computed no longer uses effect
    */
   effect: ComputedRefImpl
 }
 
+export interface ComputedRef<T = any> extends BaseComputedRef<T> {
+  readonly value: T
+}
+
+export interface WritableComputedRef<T, S = T> extends BaseComputedRef<T, S> {
+  [WritableComputedRefSymbol]: true
+}
+
 export type ComputedGetter<T> = (oldValue?: T) => T
 export type ComputedSetter<T> = (newValue: T) => void
 
index a7d959dfaaa9c8f77f9eab03bc7620a14d5ba84c..2ebb2d4e63a40796b7757e833078f8a8009542cf 100644 (file)
@@ -13,5 +13,5 @@ export const computed: typeof _computed = (
       ;(c as unknown as ComputedRefImpl<any>)._warnRecursive = true
     }
   }
-  return c
+  return c as any
 }