programing

타이프스크립트:리액트에 이력 오브젝트의 타입 체크를 추가하는 방법

lastcode 2023. 2. 26. 09:48
반응형

타이프스크립트:리액트에 이력 오브젝트의 타입 체크를 추가하는 방법

이력 오브젝트를 소품으로 받는 코드는 다음과 같습니다.

const ChildComponent = ({ history }) => (
        <div className={styles.body}>
            <div className={styles.cta}>
                <FloatingActionButton onClick={() => history.push(routes[4].path)}>
                    <span>Click me</span>
                </FloatingActionButton>
            </div>
        </div>
);

이력 프로포트의 타입 체크를 추가하려면 어떻게 해야 합니까?이 이력 프로포트의 부모에 라우터 HOC를 붙이면 됩니다.제가 생각할 수 있는 한 가지 방법은 다음과 같은 것을 쓰는 것입니다.

interface Props {
    history: {
        push(url: string): void;
    };
}

하지만 나는 이것이 올바른 방법이 아니라고 확신한다. 왜냐하면 역사 물체의 나머지 재산들이 손실되고 있기 때문이다.

올바른 방법을 제안해 주시겠습니까?

@Oblosys의 답변을 바탕으로 코드를 갱신.

import { withRouter, RouteComponentProps } from "react-router-dom";

interface Props extends RouteComponentProps<any> {
   /* Parent component's props*/
}

class Parent extends React.Component<Props, {}> {
    render() {
        return <ChildComponent history={this.props.history} />;
    }
}

//Child component related stuff
interface ChildComponentProps extends RouteComponentProps<any> {}

const ChildComponent: React.SFC<ChildComponentProps> = (props) => (
  <div className={styles.body}>
     <div className={styles.cta}>
         <FloatingActionButton onClick={() => history.push(routes[4].path)}>
            <span>Click me</span>
         </FloatingActionButton>
     </div>
   </div>
);

function mapStateToProps(state: types.AppState) {
    /* related code */
}

function mapDispatchToProps(dispatch: Redux.Dispatch<types.AppState>{
    /* related code */
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Parent));

그러나, 다음의 에러가 발생하고 있습니다.

Type '{ history: History; }' is not assignable to type 'ChildComponentProps'.
    Property 'match' is missing in type '{ history: History; }'

를 사용할 수 있습니다.RouteComponentPropsinterface: 모든 소품 통과를 선언합니다.withRouter:

import { RouteComponentProps } from 'react-router-dom';
..
interface ChildComponentProps extends RouteComponentProps<any> {
  /* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
  ..
);

type 파라미터:RouteComponentProps의 타입입니다.params에 있어서의 재산.match따라서 명명된 경로 세그먼트를 대조하지 않는 한 필요하지 않습니다.

또는 만약history출신이 아니다withRouter소품으로 전달되기 때문에 타입을 Import 할 수 있습니다.history:

import { History } from 'history';
..
interface ChildComponentProps {
  history : History
  /* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
  ..
);

내가 찾은 가장 간단한 해결책

import { RouteComponentProps } from 'react-router-dom';

....

interface Foo{
  history: RouteComponentProps["history"];
  location: RouteComponentProps['location'];
  match: RouteComponentProps['match'];
}

후크가 있는 React 16.8의 경우:

...
import {withRouter, RouteComponentProps} from 'react-router-dom';
...
const ChildComponent: React.FunctionComponent<RouteComponentProps> = ({history}) => {
...
}

언급URL : https://stackoverflow.com/questions/49342390/typescript-how-to-add-type-check-for-history-object-in-react

반응형