This commit is contained in:
Tycho 2025-06-19 14:14:53 +08:00 committed by GitHub
commit 5f2c701963
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 47 additions and 1 deletions

View File

@ -236,6 +236,38 @@ describe('Type safety for `WritableComputedRef` and `ComputedRef`', () => {
expectType<ComputedRef<string>>(immutableComputed) expectType<ComputedRef<string>>(immutableComputed)
}) })
declare class Foo {
private _: unknown
}
describe('omit the initial value and specify a generic w/ `Ref` type', <T>() => {
const a = ref<{ foo: Ref<number> }>()
expectType<{ foo: number } | undefined>(a.value)
expectType<number>(a.value!.foo)
a.value = undefined
a.value = { foo: ref(1) }
a.value!.foo = 2
// @ts-expect-error
a.value.foo.value = 2
const b = ref<Ref<number>>()
expectType<Ref<number> | undefined>(b.value)
expectType<number>(b.value!.value)
b.value = undefined
b.value = ref(1)
b.value!.value = 1
const c = ref<T>()
c.value = undefined
c.value = {} as T
// case from vueuse
const d = ref<Foo>()
expectType<Ref<Foo | undefined>>(d)
d.value = new Foo()
expectType<Foo | undefined>(d.value)
})
// shallowRef // shallowRef
type Status = 'initial' | 'ready' | 'invalidating' type Status = 'initial' | 'ready' | 'invalidating'
const shallowStatus = shallowRef<Status>('initial') const shallowStatus = shallowRef<Status>('initial')

View File

@ -1,5 +1,6 @@
import { import {
type IfAny, type IfAny,
type PublicOf,
hasChanged, hasChanged,
isArray, isArray,
isFunction, isFunction,
@ -55,7 +56,13 @@ export function isRef(r: any): r is Ref {
export function ref<T>( export function ref<T>(
value: T, value: T,
): [T] extends [Ref] ? IfAny<T, Ref<T>, T> : Ref<UnwrapRef<T>, UnwrapRef<T> | T> ): [T] extends [Ref] ? IfAny<T, Ref<T>, T> : Ref<UnwrapRef<T>, UnwrapRef<T> | T>
export function ref<T = any>(): Ref<T | undefined>
export function ref<T = any>(): [T] extends [Ref]
? Ref<T | undefined>
: PublicOf<T> extends T
? Ref<UnwrapRef<T> | undefined, UnwrapRef<T> | T | undefined>
: Ref<T | undefined>
export function ref(value?: unknown) { export function ref(value?: unknown) {
return createRef(value, false) return createRef(value, false)
} }

View File

@ -27,6 +27,13 @@ export type OverloadParameters<T extends (...args: any[]) => any> = Parameters<
OverloadUnion<T> OverloadUnion<T>
> >
/**
* Utility for strip out `private` / `protected` fields
*/
export type PublicOf<T> = {
[P in keyof T]: T[P]
}
type OverloadProps<TOverload> = Pick<TOverload, keyof TOverload> type OverloadProps<TOverload> = Pick<TOverload, keyof TOverload>
type OverloadUnionRecursive< type OverloadUnionRecursive<