[React-TypeScript] React input common component 마이그레이션. jsx에서 tsx

Doha Lee·2023년 7월 11일
0

React

목록 보기
3/7

common components를 마이그레이션 하면서 여러가지 오류들을 맞이 했다. 오류에서 배워가는 와중에 궁금증이 들었던 부분이 있다.🤔 바로 ...props 부분이었는데 작성한 컴포넌트와 스타일 컴포넌트의 타입들을 명시해주었을 때 ...props로 들어오는 속성들의 타입은 명시를 해야하는 걸까?

...Props에 타입을 미리 대응해야하는가?

import React from 'react';
import styled from 'styled-components';

type LoginInputProps = React.HTMLAttributes<HTMLInputElement> & {
  type?: 'button' | 'submit' | 'reset' | undefined;
};

const LoginInput = (props: LoginInputProps) => {
  const { type } = props;
  return <InputStyle type={type ? type : 'text'} {...props} />;
};

const InputStyle = styled.input`
  padding: 20px 10px;
  border-bottom: 1px solid var(--border);

  &::placeholder {
    font-size: 16px;
  }
`;

export default LoginInput;

현재는 LoginInput컴포넌트의 type 부분에만 예상 type을 작성해주었는데, ...props 부분은 어떻게 해야할지 몰랐다. 그래서 gpt의 도움을 받아 찾아보았다.

type LoginInputProps = React.HTMLAttributes<HTMLInputElement> & {
  type?: 'button' | 'submit' | 'reset' | undefined;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
};

위의 코드 처럼 onChange에 대한 대응을 할 수 있지만 ...props를 사용하여 모든 동적인 속성에 대해 타입을 지정하는 것은 어려울 수 있다고 한다. 따라서 일반적으로 ...props를 사용하여 동적인 속성을 전달받을 때는 타입 체크를 생략하고, 필요한 경우 속성의 유효성을 직접 확인하거나 타입 단언(assertion)을 사용하여 타입을 강제하는 것이 일반적이라고 한다.

속성의 유효성, 타입 단언

그럼 속성의 유효성을 직접 확인하거나 타입단언을 사용하여 타입을 강제하는 방법은 어떤게 있을까?

type LoginInputProps = React.HTMLAttributes<HTMLInputElement> & {
  type?: 'button' | 'submit' | 'reset' | undefined;
  onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
};

const LoginInput = (props: LoginInputProps) => {
  const { type, onChange, ...rest } = props;

  if (onChange && typeof onChange !== 'function') {
    console.error('onChange must be a function');
  }

  return <InputStyle type={type ? type : 'text'} {...rest} />;
};

위 코드에서 onChange 속성을 확인하기 위해 조건문을 사용하여 함수 타입 여부를 확인할 수 있다. 만약 속성이 함수 타입이 아니라면 콘솔에 error가 찍히도록 말이다.

또한 타입 단언을 사용하여 속성의 타입을 강제할 수도 있다. 예를 들어 '...props'로 전달받은 속성 중에서 customProp이라는 속성을 사용하고자 한다면 다음과 같이 타입 단언을 사용하여 타입을 강제할 수 있다.

type LoginInputProps = React.HTMLAttributes<HTMLInputElement> & {
  type?: 'button' | 'submit' | 'reset' | undefined;
  customProp?: string;
};

const LoginInput = (props: LoginInputProps) => {
  const { type, customProp, ...rest } = props;

  // customProp 속성을 사용할 때 타입 단언을 사용하여 타입을 강제함
  const customValue = (customProp as string) || '';

  return <InputStyle type={type ? type : 'text'} {...rest} />;
};

위 코드에서는 customProps 속성을 사용할 때 (customProp as string)이렇게 타입단언을 사용하여 해당 속성을 string으로 강제할 수 있다. 이러한 방식으로 유효성을 직접 확인하거나 타입 단언을 사용하여 필요한 경우에 타입을 강제할 수 있다. 하지만 이것은 타입 시스템의 검사를 우회하는 것이기 때문에 주의해서 사용해야한단다. 올바른 타입을 사용하는 것이 좋고, 필요한 경우에만 직접확인하거나 타입 단언을 사용하기로 하자.

0개의 댓글

관련 채용 정보