Trouble Shooting

[TypeScript] No overload matches this call.

dev_seon 2022. 9. 23. 00:37

1. 에러 발생

프로젝트를 진행하며 styled-components로 component를 생성하던 중 임의의 Props를 만들어 전달하려 하자 "No overload matches this call." 에러가 발생했습니다.

// 에러 발생 코드
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  text: string;
  width?: string;
  height?: string;
}

const Input = ({ text, ...props }: InputProps) => {
  return <InputBox placeholder={text} {...props} />;
};

export default Input;

const InputBox = styled.input<InputProps>`
  width: ${(props) => props.width ?? "500px"};
  height: ${(props) => props.height ?? "66px"};
`;

 

2. 에러 해결

방법 1) interface InputProps의 text 속성의 key 값을 text -> placeholder로 변경

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
    placeholder: string;
    width?: string;
    height?: string;
}

const Input = ({ placeholder, ...props }: InputProps) => {
    return <InputBox placeholder={placeholder} {...props} />;
};

export default Input;

const InputBox = styled.input<InputProps>`
    width: ${(props) => props.width ?? '500px'};
    height: ${(props) => props.height ?? '66px'};
`;

방법 2) InputBox의 props type을 지정할 때 interface InputProps의 text 속성을 삭제하여 type 지정

(또는 text 속성을 제외한(width, height 속성만 포함된) 새로운 interface를 선언하여 InputBox props type 지정)

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
    text: string;
    width?: string;
    height?: string;
}

const Input = ({ text, ...props }: InputProps) => {
    return <InputBox placeholder={text} {...props} />;
};

export default Input;

const InputBox = styled.input<Omit<InputProps, 'text'>>`
    width: ${(props) => props.width ?? '500px'};
    height: ${(props) => props.height ?? '66px'};
`;

 

3. 고찰

이번 프로젝트에서는 Input component를 사용하는 모든 상황에 placeholder가 필요했기 때문에 interface InputProps를 생성할 때 placeholder의 값으로 사용될 text 프로퍼티를 선택적 프로퍼티로 지정하지 않았습니다.

그러나 styled-components를 사용하여 생성한 InputBox에도 props의 타입을 InputProps로 지정하게 될 경우  InputBox의 속성으로 text가 사용되어야 했는데, text는 placeholder의 값으로 사용될 뿐 속성으로 사용되지는 않기 때문에 "No overload matches this call." 에러가 발생했습니다. 원인을 파악한 후 이를 해결하기 위해 위와 같은 방법을 적용해보았고, 에러를 해결할 수 있었습니다.