2
votes

First of all sorry if this was answered before, I couldn't find it.

For some reasons in the app I am working right now we have a wrapper for some material-ui components. For instance I have a MyCompanyButton which is a wrapper for the material-ui Button component.

It is really simple, something like this:

const MyCompanyButton: React.FC<MyCompanyButtonProps> = (props): React.ReactElement => {
  const { label, color, type } = props;

  return (
    <Button color={color} type={type}>
      {label}
    </Button>
  );
};

The problem is with the types for the props.

My first attempt was to define them as this:

type MyCompanyButtonProps = {
  label: string;
  color: string;
  type: string;
};

But when I try to use my component like this:

<MyCompanyButton color="primary" type="submit" label="Send" />

I get the following error:

Type 'string' is not assignable to type '"default" | "inherit" | "primary" | "secondary" | undefined'. TS2769

I understand the error but I do not know how to fix it. I want to reuse material-ui types, but I can't find them. I know in current versions they are built-in in the core package, but I do not understand how to find the "color" type and apply it to my color prop.

What I did so far was take the type definition from the error and apply it to my prop:

color: "default" | "inherit" | "primary" | "secondary" | undefined;

However, I think this is not the way to do it because if the type changes in the library I need to change it here too.

I hope someone can help me.

Thanks !

1

1 Answers

3
votes

Since you're doing this to extend the Button component as label is not part of the MUI Button props, you can extend your MyCompanyButtonProps type definition with the MUI ButtonProps type like this:

import { Button, ButtonProps } from '@material-ui/core';

interface MyCompanyButtonProps extends ButtonProps {
  label: string;
}

export const MyCompanyButton: React.FC<MyCompanyButtonProps> = (props): React.ReactElement => {
  const { label, color, type } = props;

  return (
    <Button color={color} type={type}>
      {label}
    </Button>
  );
};

In general with the Material UI library, the component props can be imported from the same place as the component, with Props following the component name.