Skip to content

Commit

Permalink
fix(react): fix type inference in useInjectable
Browse files Browse the repository at this point in the history
  • Loading branch information
raveclassic committed Apr 25, 2022
1 parent 1511fcd commit e5d0a4a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
9 changes: 9 additions & 0 deletions packages/react/src/use-injectable.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ import { suppressConsoleError } from './utils'
import { DependenciesProvider } from './dependencies-provider'

describe('useInjectable', () => {
it('infers the type correctly', () => {
const value = injectable(() => 123)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Component = () => {
// $ExpectType number
const v = useInjectable(value)
return v
}
})
it('throws if called not within DependenciesProvider subtree', () => {
const dispose = suppressConsoleError()
const value = injectable(() => 123)
Expand Down
12 changes: 8 additions & 4 deletions packages/react/src/use-injectable.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import {
Injectable,
InjectableDependencies,
InjectableValue,
UnknownDependencyTree,
} from '@injectable-ts/core'
import { useContext, useMemo } from 'react'
import { context } from './context'

export function useInjectable<
Input extends Injectable<UnknownDependencyTree, Value>,
Value
>(input: Input, overrides?: Partial<InjectableDependencies<Input>>): Value {
Input extends Injectable<UnknownDependencyTree, unknown>
>(
input: Input,
overrides?: Partial<InjectableDependencies<Input>>
): InjectableValue<Input> {
const dependencies = useContext(context)
if (dependencies === undefined) {
throw new Error(
Expand All @@ -18,11 +21,12 @@ export function useInjectable<
}
return useMemo(
() =>
// eslint-disable-next-line no-restricted-syntax
input(
overrides === undefined
? dependencies
: { ...dependencies, ...overrides }
),
) as InjectableValue<Input>,
[dependencies, overrides, input]
)
}

0 comments on commit e5d0a4a

Please sign in to comment.