fix(types): fix provide type checking for ref value

fix #8201
This commit is contained in:
Evan You 2023-05-01 11:26:47 +08:00
parent be389221d8
commit de87e6e405
2 changed files with 18 additions and 2 deletions

View File

@ -1,6 +1,9 @@
import { provide, inject, InjectionKey } from 'vue'
import { provide, inject, ref, Ref, InjectionKey } from 'vue'
import { expectType } from './utils'
provide('foo', 123)
provide(123, 123)
const key: InjectionKey<number> = Symbol()
provide(key, 1)
@ -14,3 +17,13 @@ expectType<number>(inject(key, () => 1, true /* treatDefaultAsFactory */))
expectType<() => number>(inject('foo', () => 1))
expectType<() => number>(inject('foo', () => 1, false))
expectType<number>(inject('foo', () => 1, true))
// #8201
type Cube = {
size: number
}
const injectionKeyRef = Symbol('key') as InjectionKey<Ref<Cube>>
// @ts-expect-error
provide(injectionKeyRef, ref({}))

View File

@ -6,7 +6,10 @@ import { warn } from './warning'
export interface InjectionKey<T> extends Symbol {}
export function provide<T>(key: InjectionKey<T> | string | number, value: T) {
export function provide<T extends InjectionKey<any>>(
key: T | string | number,
value: T extends InjectionKey<infer V> ? V : any
) {
if (!currentInstance) {
if (__DEV__) {
warn(`provide() can only be used inside setup().`)