Prechádzať zdrojové kódy

types: fix + test inject API typing

ref: #2052
Evan You 5 rokov pred
rodič
commit
b2dc95378d

+ 6 - 1
packages/runtime-core/src/apiInject.ts

@@ -31,7 +31,12 @@ export function inject<T>(key: InjectionKey<T> | string): T | undefined
 export function inject<T>(
 export function inject<T>(
   key: InjectionKey<T> | string,
   key: InjectionKey<T> | string,
   defaultValue: T,
   defaultValue: T,
-  treatDefaultAsFactory?: boolean
+  treatDefaultAsFactory?: false
+): T
+export function inject<T>(
+  key: InjectionKey<T> | string,
+  defaultValue: T | (() => T),
+  treatDefaultAsFactory: true
 ): T
 ): T
 export function inject(
 export function inject(
   key: InjectionKey<any> | string,
   key: InjectionKey<any> | string,

+ 15 - 0
test-dts/inject.test-d.ts

@@ -0,0 +1,15 @@
+import { provide, inject, InjectionKey, expectType } from './index'
+
+const key: InjectionKey<number> = Symbol()
+
+provide(key, 1)
+// @ts-expect-error
+provide(key, 'foo')
+
+expectType<number | undefined>(inject(key))
+expectType<number>(inject(key, 1))
+expectType<number>(inject(key, () => 1, true /* treatDefaultAsFactory */))
+
+expectType<() => number>(inject('foo', () => 1))
+expectType<() => number>(inject('foo', () => 1, false))
+expectType<number>(inject('foo', () => 1, true))