Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reuable typescript input components causes issues due to size param

I am trying to create a reusable React Typescript input component. One of the params for the component is "size" however its already used for input and I would like to overwrite it if possible.

So currently I have it setup like this:

import React, { forwardRef } from 'react';
import classNames from 'classnames';

type IInputProps = {
  name?: string;
  size?: 's' | 'm';
  status?: '' | 'disabled' | 'invalid';
} & React.ComponentPropsWithRef<'input'>;

const Input = forwardRef<HTMLInputElement, IInputProps>(
  ({ name, size = 'm', status = '', ...rest }: IInputProps, ref) => {
    const inputClassNames = classNames(
      'text-dark w-full ring-2 rounded-full py-1.5 px-3 tracking-wider dark:bg-bright',
      {
        'ring-transparent hover:ring-cyan hover:dark:ring-bright/10 focus-within:outline-none focus-within:border-none focus:ring-cyan':
          status !== 'invalid',
        'ring-transparent border-1 border-amber-600 focus-within:outline-none ':
          status === 'invalid',
        'h-12': size === 'm',
        'text-sm h-10': size === 's',
        'opacity-50': status === 'disabled',
      },
    );

    return (
      <div className='w-full'>
        <input ref={ref} id={name} name={name} className={inputClassNames} {...rest} />
      </div>
    );
  },
);

Input.displayName = 'Input';

export default Input;

Now typescript is complaining about size with this issue:
TS2322: Type  string  is not assignable to type  never 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Anyone know how I can fix this?

>Solution :

You could omit the size property from ComponentPropsWithRef to overwrite it with your own size property.

type IInputProps = {
  name?: string;
  size?: 's' | 'm';
  status?: '' | 'disabled' | 'invalid';
} & Omit<React.ComponentPropsWithRef<'input'>, 'size'>;

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading