Skip to content

Commit

Permalink
fix(types/computed): ensure type safety for WritableComputedRef (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
jh-leong committed Aug 14, 2024
1 parent 3bda3e8 commit 5cf5a16
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
8 changes: 8 additions & 0 deletions packages-private/dts-test/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
15 changes: 10 additions & 5 deletions packages/reactivity/src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-core/src/apiComputed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ export const computed: typeof _computed = (
;(c as unknown as ComputedRefImpl<any>)._warnRecursive = true
}
}
return c
return c as any
}

0 comments on commit 5cf5a16

Please sign in to comment.