简体   繁体   中英

Do I have to declare placeholder on my reusable input in React with typescript?

I'm creating a React components library with Typescript and have a question. Do I have to declare every single input properties in type/interface when creating a reusable component?

I have an input field created with styled components like this:

import React from 'react';

import { StyledInput } from './styles';

interface Props {
  type?: 'text' | 'password' | 'number' | 'tel' | 'time';
  name: string;
}

const Input: React.FC<Props> = ({ type = 'text', name, ...rest }) => {
  return <StyledInput type={type} name={name} {...rest} />;
};

export default Input;

I'm trying to use this with placeholder, for example. Typescript throws this error:

Type '{ name: string; placeholder: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
Property 'placeholder' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.ts(2322)

As placeholder is intrinsic Input property, I thought it was resolved when I spread props {...rest} . Input doesn't already knows that placeholder is a string prop? Or onChange is a function, or onFocus?

Let me know if this question doesn't make any sense.

Cheers!

You have to be explicit when declaring the types. Spreading the props {...rest} doesn't resolve the types for the custom Input component.

interface IProps extends React.HTMLProps<HTMLInputElement> {
   // type any custom props you want to pass other than-
   // existing props for a input like "placeholder", "name" or "type"
}

React.HTMLProps<HTMLInputElement> will include types for all the default attributes that can be passed to a input element. But if you want the custom Input component to receive some other custom props as well you have to declare the type for it in the interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM