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

fix(types): make toRef return correct type(fix #4732) #4734

Merged
merged 2 commits into from Oct 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/reactivity/src/ref.ts
Expand Up @@ -65,7 +65,9 @@ export function isRef(r: any): r is Ref {
return Boolean(r && r.__v_isRef === true)
}

export function ref<T extends object>(value: T): ToRef<T>
export function ref<T extends object>(
value: T
): [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
export function ref<T>(value: T): Ref<UnwrapRef<T>>
export function ref<T = any>(): Ref<T | undefined>
export function ref(value?: unknown) {
Expand Down Expand Up @@ -212,7 +214,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
}
}

export type ToRef<T> = [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
export type ToRef<T> = [T] extends [Ref] ? T : Ref<T>
export function toRef<T extends object, K extends keyof T>(
object: T,
key: K
Expand Down
13 changes: 13 additions & 0 deletions test-dts/ref.test-d.ts
Expand Up @@ -10,6 +10,7 @@ import {
toRef,
toRefs,
ToRefs,
shallowReactive,
watch
} from './index'

Expand Down Expand Up @@ -236,3 +237,15 @@ function testUnrefGenerics<T>(p: T | Ref<T>) {
}

testUnrefGenerics(1)

// #4732
const baz = shallowReactive({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: type-only tests should be done in the test-dts directory.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your careful guidance, I will be careful next time.😃

foo: {
bar: ref(42)
}
})

const foo = toRef(baz, 'foo')

expectType<Ref<number>>(foo.value.bar)
expectType<number>(foo.value.bar.value)