1

My IDE is showing 2 errors in this typescript (tsx) snippet:

// @ next line: TS2300: Duplicate identifier 'boolean'.
const SlidesControl = ({ previous: boolean, next: boolean }) => {

  return (
    // @ next line: TS2304: Cannot find names 'previous' and 'next'.
    <nav>TODO {previous} {next}</nav>
  )
}

Why?

dragonmnl
  • 14,578
  • 33
  • 84
  • 129

1 Answers1

4

const SlidesControl = ({ previous: boolean, next: boolean }) - rename params (JS feature, ES6), in your case 2 parameters with name boolean

You need type description (TS feature):

const SlidesControl = ({ previous, next }: { previous: boolean, next: boolean }) => {
    return (
        <nav>TODO {previous} {next}</nav>
    );
};

Another way:

type ISlidesControlProps = { previous: boolean; next: boolean };

const SlidesControl = ({ previous, next }: ISlidesControlProps) => {
    return (
        <nav>
            TODO {previous} {next}
        </nav>
    );
};

More preferred way in React:

type ISlidesControlProps = { previous: boolean; next: boolean };

const SlidesControl: React.FC<ISlidesControlProps> = ({ previous, next }) => {
    return (
        <nav>
            TODO {previous} {next}
        </nav>
    );
};
Nikita Madeev
  • 4,284
  • 9
  • 20
  • thanks. isn't there a more compact syntax than rewriting each parameter to specify the type? – dragonmnl Jun 03 '20 at 10:54
  • @dragonmnl No, another way create type outside component: `type ISlidesControlProps = { previous: boolean; next: boolean };` and use: `const SlidesControl = ({ previous, next }: ISlidesControlProps) =>` – Nikita Madeev Jun 03 '20 at 10:56
  • Best practice in React: `const SlidesControl: React.FC = ({ previous, next })` – Nikita Madeev Jun 03 '20 at 10:58