Skip to content

Commit a0fd477

Browse files
Tresautay1orjones
andauthored
feat: add TypeScript types for ErrorBoundary and ErrorBoundaryContext (#15348)
Co-authored-by: Taylor Jones <[email protected]>
1 parent d1215c3 commit a0fd477

File tree

3 files changed

+22
-8
lines changed

3 files changed

+22
-8
lines changed

packages/react/src/components/ErrorBoundary/ErrorBoundary.js renamed to packages/react/src/components/ErrorBoundary/ErrorBoundary.tsx

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8-
import React from 'react';
8+
import React, { ErrorInfo, ReactNode } from 'react';
99
import PropTypes from 'prop-types';
1010
import { ErrorBoundaryContext } from './ErrorBoundaryContext';
1111

@@ -26,29 +26,39 @@ import { ErrorBoundaryContext } from './ErrorBoundaryContext';
2626
* Reference:
2727
* https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
2828
*/
29-
export default class ErrorBoundary extends React.Component {
29+
interface ErrorBoundaryProps {
30+
children?: ReactNode;
31+
fallback?: ReactNode;
32+
}
33+
34+
interface ErrorBoundaryState {
35+
hasError: boolean;
36+
}
37+
38+
export default class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
3039
static propTypes = {
3140
children: PropTypes.node,
3241
fallback: PropTypes.node,
3342
};
3443

3544
static contextType = ErrorBoundaryContext;
45+
context!: React.ContextType<typeof ErrorBoundaryContext>;
3646

37-
static getDerivedStateFromError() {
47+
static getDerivedStateFromError(): ErrorBoundaryState {
3848
return {
3949
hasError: true,
4050
};
4151
}
4252

43-
state = {
53+
state: ErrorBoundaryState = {
4454
hasError: false,
4555
};
4656

47-
componentDidCatch(error, info) {
57+
componentDidCatch(error: Error, info: ErrorInfo) {
4858
this.context.log(error, info);
4959
}
5060

51-
componentDidUpdate(prevProps) {
61+
componentDidUpdate(prevProps: ErrorBoundaryProps) {
5262
if (prevProps.children !== this.props.children) {
5363
this.setState({ hasError: false });
5464
}

packages/react/src/components/ErrorBoundary/ErrorBoundaryContext.js renamed to packages/react/src/components/ErrorBoundary/ErrorBoundaryContext.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8-
import { createContext } from 'react';
8+
import { ErrorInfo, createContext } from 'react';
99

10-
export const ErrorBoundaryContext = createContext({
10+
export interface ErrorBoundaryContextType {
11+
log: (error: Error, errorInfo: ErrorInfo) => void;
12+
}
13+
14+
export const ErrorBoundaryContext = createContext<ErrorBoundaryContextType>({
1115
log(error, info) {
1216
console.log(info.componentStack);
1317
},

0 commit comments

Comments
 (0)