Skip to content

Commit 5cf5a16

Browse files
authored
fix(types/computed): ensure type safety for WritableComputedRef (#11608)
1 parent 3bda3e8 commit 5cf5a16

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

Diff for: packages-private/dts-test/ref.test-d.ts

+8
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,14 @@ describe('allow computed getter and setter types to be unrelated', () => {
209209
expectType<string>(c.value)
210210
})
211211

212+
describe('Type safety for `WritableComputedRef` and `ComputedRef`', () => {
213+
// @ts-expect-error
214+
const writableComputed: WritableComputedRef<string> = computed(() => '')
215+
// should allow
216+
const immutableComputed: ComputedRef<string> = writableComputed
217+
expectType<ComputedRef<string>>(immutableComputed)
218+
})
219+
212220
// shallowRef
213221
type Status = 'initial' | 'ready' | 'invalidating'
214222
const shallowStatus = shallowRef<Status>('initial')

Diff for: packages/reactivity/src/computed.ts

+10-5
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,24 @@ import { Dep, globalVersion } from './dep'
1414
import { ReactiveFlags, TrackOpTypes } from './constants'
1515

1616
declare const ComputedRefSymbol: unique symbol
17+
declare const WritableComputedRefSymbol: unique symbol
1718

18-
export interface ComputedRef<T = any> extends WritableComputedRef<T> {
19-
readonly value: T
19+
interface BaseComputedRef<T, S = T> extends Ref<T, S> {
2020
[ComputedRefSymbol]: true
21-
}
22-
23-
export interface WritableComputedRef<T, S = T> extends Ref<T, S> {
2421
/**
2522
* @deprecated computed no longer uses effect
2623
*/
2724
effect: ComputedRefImpl
2825
}
2926

27+
export interface ComputedRef<T = any> extends BaseComputedRef<T> {
28+
readonly value: T
29+
}
30+
31+
export interface WritableComputedRef<T, S = T> extends BaseComputedRef<T, S> {
32+
[WritableComputedRefSymbol]: true
33+
}
34+
3035
export type ComputedGetter<T> = (oldValue?: T) => T
3136
export type ComputedSetter<T> = (newValue: T) => void
3237

Diff for: packages/runtime-core/src/apiComputed.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,5 @@ export const computed: typeof _computed = (
1313
;(c as unknown as ComputedRefImpl<any>)._warnRecursive = true
1414
}
1515
}
16-
return c
16+
return c as any
1717
}

0 commit comments

Comments
 (0)