TypeScript Course
TypeScript
/
Beginner

React: Typing Props

Definition

Using TypeScript Interfaces or Type Aliases to define the exact shape of properties (props) a React component accepts.

Explain Like I'm New

Typing props is giving your React component a bouncer at the door. If a parent component tries to pass a prop that isn't on the guest list (the Interface), or tries to pass a Number when a String was expected, the bouncer rejects it instantly.

Real World Example

Typing a ProfileCard component to require a `name: string` and an `age: number`, with an optional `avatarUrl?: string`.

Common Use Cases

  • •Self-documenting React components
  • •Preventing UI crashes from missing data

Interactive Example

import React from 'react';

type ButtonProps = {
  label: string;           // Required string
  onClick: () => void;     // Required function
  isDisabled?: boolean;    // Optional boolean
  children?: React.ReactNode; // Optional React elements inside the tag
};

// Modern approach: Typing the arguments directly
export function Button({ label, onClick, isDisabled = false, children }: ButtonProps) {
  return (
    <button onClick={onClick} disabled={isDisabled}>
      {label}
      {children}
    </button>
  );
}

// USAGE (TS will throw an error if 'label' or 'onClick' are missing!)
// <Button label="Submit" onClick={() => console.log('Clicked')} />

Interview Questions

basic

  • Should you use `type` or `interface` for React Props?

intermediate

  • How do you type a prop that accepts React children (like `<div>...</div>`)?

advanced

  • What is `React.FC` and why is it currently discouraged by many developers?

Flash Cards

Question

type vs interface for Props?

Click to reveal answer
Answer

Both work perfectly. `type` is generally preferred by modern teams for props because props don't need to be extended or declaration-merged later, and `type` handles Unions better.

Question

How to type children?

Click to reveal answer
Answer

Use `children: React.ReactNode`. This allows strings, numbers, React elements, fragments, or arrays of elements.

Question

Why is React.FC discouraged?

Click to reveal answer
Answer

Historically, `React.FC` implicitly injected the `children` prop into every component, even if your component shouldn't accept children. It also struggles with Generic components. Modern practice is to type the props directly: `function Button(props: ButtonProps) {}`.