'((e:ChangeEvent <HTMLInputElement>)=> void'不能分配给类型'((event:ChangeEvent <HTMLInputElement>)=> void)

时间:2020-02-06 07:02:29

标签: reactjs typescript styled-components

export interface InputProps {
    type?: string;
    name?: string;
    value?: CommonTypeTuple;
    placeholder?: string;
    label?: string;
    error?: string;
    helpText?: string;
    block?: boolean;
    disabled?: boolean;
    onChange?: ChangeHandler<string>;
    onBlur?: BlurHandler<string | number>;
}

export const Input = ({
    type = "text",
    name = "",
    placeholder,
    error,
    block = false,
    disabled = false,
    onChange = () => {},
    onBlur = () => {},
    value,
    className = "",
    ...rest
}: InputProps & React.InputHTMLAttributes<HTMLInputElement>) => {
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        onChange(e.target.value, e.target.name);
    };
    const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
        onBlur(e.target.value);
    };
    return (
        <StyledWrapper block={block}>
            <StyledInput
                name={name}
                type={type}
                placeholder={placeholder}
                error={error}
                disabled={disabled}
                onBlur={handleBlur}
                onChange={handleChange}
                value={value}
                className={className}
                aria-label="tm-input"
                {...rest}
            />
        </StyledWrapper>
    );
};

export const StyledInput = styled.input<InputProps>`
...
...

onChangeonBlur报告错误

(e: ChangeEvent<HTMLInputElement>) => void' is not assignable to type '((event: ChangeEvent<HTMLInputElement>) => void) & ChangeHandler<string>'.
Type '(e: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type 'ChangeHandler<string>'.
   Types of parameters 'e' and 'value' are incompatible.
     Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement>'.ts(2322)
index.d.ts(1977, 9): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, "type" | ... 283 more ... | "key"> & { ...; } & InputProps, "type" | ... 288 more ... | "key"> & Partial<...>

我很困惑,因为我显然传递了e.target.value这是一个字符串,并且报告的错误假定它期望两个本机onChange和自定义handleChange的处理程序函数具有不同的签名,一样。

1 个答案:

答案 0 :(得分:1)

React.InputHTMLAttributes<HTMLInputElement>onChange定义为(event: ChangeEvent<HTMLInputElement>) => void),而您正在将onChange定义为ChangeHandler<string>。您在错误消息中看到的类型是这两种类型的intersection

您可能要使用Omit<T, K>来移除重叠的道具:

type ReactInput = React.InputHTMLAttributes<HTMLInputElement>;
type InputArgs = InputProps & Omit<ReactInput, keyof InputProps>
export const Input = ({ ...{}, ...rest }: InputArgs) => { ... }