Jonathan
Jonathan

Reputation: 599

What is the purpose of export interface Props in React (Typescript ver)

In the Creating a component section of React Typescript Starter example, Creating a component, there is a basic React component in Typescript:

// src/components/Hello.tsx

import * as React from 'react';

export interface Props {
  name: string;
  enthusiasmLevel?: number;
}

function Hello({ name, enthusiasmLevel = 1 }: Props) {
  if (enthusiasmLevel <= 0) {
    throw new Error('You could be a little more enthusiastic. :D');
  }

  return (
    <div className="hello">
      <div className="greeting">
        Hello {name + getExclamationMarks(enthusiasmLevel)}
      </div>
    </div>
  );
}

export default Hello;

// helpers

function getExclamationMarks(numChars: number) {
  return Array(numChars + 1).join('!');
}

I am new to Typescript. It seems that the interface Props is used by Typescript to do props type checks (similar to what the Proptypes npm package does). So the question is:

  1. If I am already using this kind of Typescript interface syntax do to props type check, do I still need to use Proptypes package like this in the same component?
    import PropTypes from 'prop-types';

    Hello.propTypes = {
      name: PropTypes.string,
      enthusiasmLevel: PropTypes.number
    };
  1. Besides, why does here use export interface? what is the purpose of exporting the interface Props? Is it compulsory?

Upvotes: 13

Views: 44602

Answers (1)

Jonas Praem
Jonas Praem

Reputation: 2444

Firstly I recommend declaring your components the ES6 way

const Hello: React.FC<IHello> = ({ name, enthusiasmLevel = 1 }) => {}

Your interface defines the contract of your component / The accepted parameters

export interface IHello {
  name: string;
  enthusiasmLevel?: number;
}

You are exporting this, so you can import your interface from other files / components which want to make use of the Hello component. For example you can use your Hello component like so from another component:

const props: IHello = {
    name: "John",
    enthusiamsLevel: 5
}

<Hello {...props} />

If I am already using this kind of Typescript interface syntax do to props type check, do I still need to use Proptypes in the same component?

You always want type strong definitions in TypeScript. So when declaring your prop variable in another component, you don't want to do const props: any = { If you decide to change your interface declaration for this component later on, you would be forced to update all your references which uses this interface. - You might want to require 1 more prop variable and in that case you would want to update your usages of this interface. If you are not used to TypeScript this can seem quite hideous at first - but the benefit of always having strong type definitions will show over time. Especially when you update your type definitions.

Upvotes: 18

Related Questions