Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(reactivity): enhance type inference for context-sensitive inputs #9516

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion packages/dts-test/reactivity.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { ref, readonly, shallowReadonly, Ref, reactive, markRaw } from 'vue'
import {
ref,
readonly,
shallowReadonly,
Ref,
reactive,
markRaw,
ComputedRef,
computed
} from 'vue'
import { describe, expectType } from './utils'

describe('should support DeepReadonly', () => {
Expand Down Expand Up @@ -62,3 +71,23 @@ describe('should unwrap tuple correctly', () => {
const reactiveTuple = reactive(tuple)
expectType<Ref<number>>(reactiveTuple[0])
})

// #1930
describe('should unwrap the computed type', () => {
interface Bar {
a: number
b: (_: any) => void
}

const computedA: ComputedRef<number> = computed(() => 1)

expectType<{ a: number }>(reactive({ a: computedA }))

expectType<Bar>(
reactive({
a: computedA, // issue happens here, but is should be okay
// @ts-expect-error
b: _ => {} // error depending on --noImplicitAny
})
)
})
5 changes: 5 additions & 0 deletions packages/reactivity/src/reactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ function getTargetType(value: Target) {
// only unwrap nested ref
export type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>

type NoInfer<T> = [T][T extends any ? 0 : never]

/**
* Returns a reactive proxy of the object.
*
Expand All @@ -80,6 +82,9 @@ export type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>
* @see {@link https://vuejs.org/api/reactivity-core.html#reactive}
*/
export function reactive<T extends object>(target: T): UnwrapNestedRefs<T>
export function reactive<T extends object>(
target: T
): NoInfer<UnwrapNestedRefs<T>>
export function reactive(target: object) {
// if trying to observe a readonly proxy, return the readonly version.
if (isReadonly(target)) {
Expand Down