Forráskód Böngészése

@uppy/core: add generic to `getPlugin` (#5247)

* @uppy/core: add generic to `getPlugin`

* Set default
Merlijn Vos 10 hónapja
szülő
commit
b6a0250f42
2 módosított fájl, 17 hozzáadás és 3 törlés
  1. 4 2
      packages/@uppy/core/src/Uppy.ts
  2. 13 1
      packages/@uppy/core/src/types.test.ts

+ 4 - 2
packages/@uppy/core/src/Uppy.ts

@@ -1724,10 +1724,12 @@ export class Uppy<M extends Meta, B extends Body = Record<string, never>> {
   /**
    * Find one Plugin by name.
    */
-  getPlugin(id: string): UnknownPlugin<M, B> | undefined {
+  getPlugin<T extends UnknownPlugin<M, B> = UnknownPlugin<M, B>>(
+    id: string,
+  ): T | undefined {
     for (const plugins of Object.values(this.#plugins)) {
       const foundPlugin = plugins.find((plugin) => plugin.id === id)
-      if (foundPlugin != null) return foundPlugin
+      if (foundPlugin != null) return foundPlugin as T
     }
     return undefined
   }

+ 13 - 1
packages/@uppy/core/src/types.test.ts

@@ -1,7 +1,7 @@
 import { expectTypeOf, test } from 'vitest'
 
 import type { Body, InternalMetadata, Meta } from '@uppy/utils/lib/UppyFile'
-import Uppy from './Uppy'
+import Uppy, { type UnknownPlugin } from './Uppy'
 import UIPlugin, { type UIPluginOptions } from './UIPlugin'
 
 interface Opts extends UIPluginOptions {
@@ -25,6 +25,18 @@ test('can .use() a plugin', async () => {
   expectTypeOf(core).toEqualTypeOf<Uppy<Meta, Record<string, never>>>()
 })
 
+test('can .getPlugin() with a generic', async () => {
+  const core = new Uppy().use(TestPlugin)
+  const plugin = core.getPlugin<TestPlugin<any, any>>('TestPlugin')
+  const plugin2 = core.getPlugin('TestPlugin')
+  expectTypeOf(plugin).toEqualTypeOf<TestPlugin<any, any> | undefined>()
+  expectTypeOf(plugin2).toEqualTypeOf<
+    // The default type
+    | UnknownPlugin<Meta, Record<string, never>, Record<string, unknown>>
+    | undefined
+  >()
+})
+
 test('Meta and Body generic move through the Uppy class', async () => {
   type M = { foo: string }
   type B = { bar: string }