fix(types): improve type constraints for provide function

This commit is contained in:
Bunny Chang 2025-03-06 00:52:36 +08:00
parent 4b1931cf89
commit 361d108f61
No known key found for this signature in database
GPG Key ID: 93576A20C7176E83
2 changed files with 8 additions and 5 deletions

View File

@ -11,7 +11,11 @@ import { expectType } from './utils'
// non-symbol keys
provide('foo', 123)
// @ts-expect-error
provide(123, 123)
// @ts-expect-error
provide(true, 123)
provide('true', 123)
const key: InjectionKey<number> = Symbol()
@ -41,7 +45,6 @@ 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

View File

@ -8,10 +8,10 @@ interface InjectionConstraint<T> {}
export type InjectionKey<T> = symbol & InjectionConstraint<T>
export function provide<T, K = InjectionKey<T> | string | number>(
key: K,
value: K extends InjectionKey<infer V> ? V : T,
): void {
export function provide<
T,
K extends InjectionKey<T> | string = InjectionKey<T> | string,
>(key: K, value: K extends InjectionKey<infer V> ? V : T): void {
if (!currentInstance) {
if (__DEV__) {
warn(`provide() can only be used inside setup().`)