Skip to content

Commit 76cad6f

Browse files
authored
fix: Rearrange observer type definitions to allow wrapping custom HOC (mobxjs#4576)
1 parent 74f26b5 commit 76cad6f

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

packages/mobx-react-lite/__tests__/observer.test.tsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,33 @@ test("useImperativeHandle and forwardRef should work with useObserver", () => {
594594
expect(consoleWarnMock).toMatchSnapshot()
595595
})
596596

597+
test("observer should work with custom HOC and infer correct type", () => {
598+
const validateChildrenWrapper = <T extends {}>(component: React.FC<T>): React.FC<T> => {
599+
const wrapper: React.FC<T> = (...args) => {
600+
const result = component(...args)
601+
if (result && React.isValidElement(result) && result.type === "div") {
602+
return result
603+
}
604+
throw new Error("Only <div> allowed as root element")
605+
}
606+
wrapper.displayName = component.displayName || component.name
607+
return wrapper
608+
}
609+
610+
interface IProps {
611+
value: string
612+
}
613+
614+
const TestComponent: React.FC<IProps> = observer(
615+
validateChildrenWrapper(function TestComponent({ value }) {
616+
return <div>{value}</div>
617+
})
618+
)
619+
620+
const rendered = render(<TestComponent value="1" />)
621+
expect(rendered.container.querySelector("div")!.innerHTML).toBe("1")
622+
})
623+
597624
it("should hoist known statics only", () => {
598625
function isNumber() {
599626
return null

packages/mobx-react-lite/src/observer.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,19 +44,18 @@ export function observer<P extends object, TRef = {}>(
4444
React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
4545
>
4646

47+
export function observer<P extends object>(
48+
baseComponent: React.FunctionComponent<P>,
49+
options?: IObserverOptions
50+
): React.FunctionComponent<P>
51+
4752
export function observer<P extends object, TRef = {}>(
4853
baseComponent: React.ForwardRefExoticComponent<
4954
React.PropsWithoutRef<P> & React.RefAttributes<TRef>
5055
>
5156
): React.MemoExoticComponent<
5257
React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
5358
>
54-
55-
export function observer<P extends object>(
56-
baseComponent: React.FunctionComponent<P>,
57-
options?: IObserverOptions
58-
): React.FunctionComponent<P>
59-
6059
export function observer<
6160
C extends React.FunctionComponent<any> | React.ForwardRefRenderFunction<any>,
6261
Options extends IObserverOptions

0 commit comments

Comments
 (0)