Skip to content

Commit a01675e

Browse files
feat(types): allow computed getter and setter types to be unrelated (#11472)
close #7271
1 parent 5ffd1a8 commit a01675e

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

packages/dts-test/ref.test-d.ts

+20
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,26 @@ describe('allow getter and setter types to be unrelated', <T>() => {
184184
e.value = d
185185
})
186186

187+
// computed
188+
describe('allow computed getter and setter types to be unrelated', () => {
189+
const obj = ref({
190+
name: 'foo',
191+
})
192+
193+
const c = computed({
194+
get() {
195+
return JSON.stringify(obj.value)
196+
},
197+
set(val: typeof obj.value) {
198+
obj.value = val
199+
},
200+
})
201+
202+
c.value = { name: 'bar' } // object
203+
204+
expectType<string>(c.value)
205+
})
206+
187207
// shallowRef
188208
type Status = 'initial' | 'ready' | 'invalidating'
189209
const shallowStatus = shallowRef<Status>('initial')

packages/reactivity/src/computed.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export interface ComputedRef<T = any> extends WritableComputedRef<T> {
2020
[ComputedRefSymbol]: true
2121
}
2222

23-
export interface WritableComputedRef<T> extends Ref<T> {
23+
export interface WritableComputedRef<T, S = T> extends Ref<T, S> {
2424
/**
2525
* @deprecated computed no longer uses effect
2626
*/
@@ -30,9 +30,9 @@ export interface WritableComputedRef<T> extends Ref<T> {
3030
export type ComputedGetter<T> = (oldValue?: T) => T
3131
export type ComputedSetter<T> = (newValue: T) => void
3232

33-
export interface WritableComputedOptions<T> {
33+
export interface WritableComputedOptions<T, S = T> {
3434
get: ComputedGetter<T>
35-
set: ComputedSetter<T>
35+
set: ComputedSetter<S>
3636
}
3737

3838
/**
@@ -175,10 +175,10 @@ export function computed<T>(
175175
getter: ComputedGetter<T>,
176176
debugOptions?: DebuggerOptions,
177177
): ComputedRef<T>
178-
export function computed<T>(
179-
options: WritableComputedOptions<T>,
178+
export function computed<T, S = T>(
179+
options: WritableComputedOptions<T, S>,
180180
debugOptions?: DebuggerOptions,
181-
): WritableComputedRef<T>
181+
): WritableComputedRef<T, S>
182182
export function computed<T>(
183183
getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T>,
184184
debugOptions?: DebuggerOptions,

0 commit comments

Comments
 (0)