Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@uppy/core: add generic to getPlugin #5247

Merged
merged 2 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/@uppy/core/src/Uppy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
14 changes: 13 additions & 1 deletion packages/@uppy/core/src/types.test.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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 }
Expand Down