Use Function Component to Define Types

  • no need for prop-types package
  • alias FC for FunctionComponent interface
  • generic type
  • pass it type as argument, and component's props will consist of the definted type and the component's children
interface WelcomeProps {}
name: string;
}
const Welcome: React.FC<WelcomeProps> = (props) => {
return <h1>Hello, {props.name}</h1>;
};
const element = <Welcome name="Sara" />;
ReactDOM.render(element, document.getElementById("root"));

or less verbose

const Welcome: React.FC<{ name: string }> = ({ name }) => (
<h1>Hello, {name}</h1>
);

Example use case for array of objects

src/types.ts

export interface Course {
name: string;
}
export interface CoursePart {
name: string;
exerciseCount: number;
}
export interface CourseParts {
courseParts: CoursePart[];
}

src/components/Content.ts

import React from 'react';
import { CourseParts } from '../types'
const Content: React.FC<CourseParts> = ({ courseParts}) => {
return (
<>
{courseParts.map(part => {
return <p key={part.name}>{part.name} {part.exerciseCount}</p>
})}
</>
)
}
export default Content