Skip to content

Commit

Permalink
fix(types): retain compatibility for provide() usage with explicit ty…
Browse files Browse the repository at this point in the history
…pe parameter
  • Loading branch information
yyx990803 committed May 2, 2023
1 parent d40d4a3 commit 038cd83
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
13 changes: 13 additions & 0 deletions packages/dts-test/inject.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { provide, inject, ref, Ref, InjectionKey } from 'vue'
import { expectType } from './utils'

// non-symbol keys
provide('foo', 123)
provide(123, 123)

Expand All @@ -9,6 +10,8 @@ const key: InjectionKey<number> = Symbol()
provide(key, 1)
// @ts-expect-error
provide(key, 'foo')
// @ts-expect-error
provide(key, null)

expectType<number | undefined>(inject(key))
expectType<number>(inject(key, 1))
Expand All @@ -27,3 +30,13 @@ const injectionKeyRef = Symbol('key') as InjectionKey<Ref<Cube>>

// @ts-expect-error
provide(injectionKeyRef, ref({}))

// naive-ui: explicit provide type parameter
provide<Cube>('cube', { size: 123 })
provide<Cube>(123, { size: 123 })
provide<Cube>(injectionKeyRef, { size: 123 })

// @ts-expect-error
provide<Cube>('cube', { size: 'foo' })
// @ts-expect-error
provide<Cube>(123, { size: 'foo' })
6 changes: 3 additions & 3 deletions packages/runtime-core/src/apiInject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { warn } from './warning'

export interface InjectionKey<T> extends Symbol {}

export function provide<T extends InjectionKey<any>>(
key: T | string | number,
value: T extends InjectionKey<infer V> ? V : any
export function provide<T, K = InjectionKey<T> | string | number>(
key: K,
value: K extends InjectionKey<infer V> ? V : T
) {
if (!currentInstance) {
if (__DEV__) {
Expand Down

0 comments on commit 038cd83

Please sign in to comment.