TypeScript Basics

Back

Loading concept...

TypeScript Basics for React 🎯

The Story of the Helpful Label Maker

Imagine you have a toy box. You can put any toy inside — cars, dolls, blocks, anything! But sometimes, you forget what’s inside. You reach in expecting a car… and pull out a doll. Oops!

TypeScript is like putting labels on everything. Before you put something in the box, you write what it is on a label. Now you always know what’s inside. No surprises!

🎯 TypeScript = JavaScript + Labels (Types) It helps you avoid mistakes by telling you what everything is.


đź”§ TypeScript Setup

What Does “Setup” Mean?

Before you can use labels, you need the label maker! Setting up TypeScript means getting your project ready to use it.

Step 1: Create a React + TypeScript Project

The easiest way is to start fresh:

npx create-react-app my-app
  --template typescript

That’s it! React gives you everything you need.

Step 2: What Files Change?

Before (JavaScript) After (TypeScript)
App.js App.tsx
index.js index.tsx

The .tsx extension means: “This file has TypeScript AND React.”

Step 3: The Config File

TypeScript uses a file called tsconfig.json. It tells TypeScript how strict to be.

{
  "compilerOptions": {
    "strict": true,
    "jsx": "react-jsx"
  }
}

💡 Think of it like this: The config file is like setting rules for your label maker. “Always check labels? Yes!”


đź§± Typing Components

What is a Component?

A component is like a LEGO brick. You build your app by sticking components together.

The Two Types of Components

graph TD A["React Components"] --> B["Function Components"] A --> C["Class Components"] B --> D["Most Popular Today!"]

Typing a Function Component

Here’s a simple component with TypeScript:

const Greeting: React.FC = () => {
  return <h1>Hello!</h1>;
};

What does React.FC mean?

  • React = the React library
  • FC = Function Component
  • Together = “This is a React function component”

A Component That Shows Your Name

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

Here, name: string is our label saying “name is always text.”

🎯 Key Insight: When you type a component, you’re telling React: “Trust me, this is a valid component.”


📦 Typing Props

What Are Props?

Props are like gifts you give to a component. You pass information from parent to child.

Without TypeScript:

// We have no idea what props to expect!
function Card(props) {
  return <div>{props.title}</div>;
}

With TypeScript:

// Now we KNOW exactly what to expect!
type CardProps = {
  title: string;
};

function Card(props: CardProps) {
  return <div>{props.title}</div>;
}

Creating a Props Type

Think of it like writing a checklist before someone gives you a gift:

type UserCardProps = {
  name: string;      // Must be text
  age: number;       // Must be a number
  isOnline: boolean; // Must be true/false
};

Using Props in a Component

type GreetingProps = {
  name: string;
  excited: boolean;
};

const Greeting: React.FC<GreetingProps> =
  ({ name, excited }) => {
  return (
    <h1>
      Hello, {name}
      {excited ? "!" : "."}
    </h1>
  );
};

Optional Props

What if a prop is optional? Use the ? symbol:

type ButtonProps = {
  text: string;
  color?: string; // Optional!
};

Now color can be provided… or not!

Props Flow

graph TD A["Parent Component"] -->|passes props| B["Child Component"] B -->|uses props| C["Display on Screen"] D["TypeScript"] -->|checks types| A D -->|checks types| B

💡 Real Example: It’s like ordering pizza. You MUST say what size (required). But extra cheese? That’s optional!


🔄 Typing State

What is State?

State is like a component’s memory. It remembers things that can change.

Example: A counter remembers the current count. A form remembers what you typed.

Using useState with TypeScript

import { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] =
    useState<number>(0);

  return (
    <button onClick={() =>
      setCount(count + 1)}>
      Count: {count}
    </button>
  );
};

What’s useState<number>(0)?

  • useState = the hook that creates state
  • <number> = the type label (this state holds a number)
  • (0) = the starting value

Common State Types

Type Example Use Case
string useState<string>("") Text input
number useState<number>(0) Counters
boolean useState<boolean>(false) Toggles
array useState<string[]>([]) Lists

Typing Complex State

What if state is an object?

type User = {
  name: string;
  age: number;
};

const [user, setUser] =
  useState<User | null>(null);

What’s User | null?

It means: “This can be a User object OR null (nothing yet).”

State Flow

graph TD A["Initial State"] -->|User action| B["setState called"] B -->|TypeScript checks| C{Is type correct?} C -->|Yes| D["State updates"] C -->|No| E["Error! Fix it!"] D --> F["Component re-renders"]

Updating Object State Safely

type Profile = {
  name: string;
  bio: string;
};

const [profile, setProfile] =
  useState<Profile>({
    name: "Alex",
    bio: "Loves coding"
  });

// Update only the bio
setProfile(prev => ({
  ...prev,
  bio: "Loves TypeScript!"
}));

🎯 Why This Matters: TypeScript stops you from accidentally putting a number where text should go. No more mysterious bugs!


🌟 Putting It All Together

Here’s a complete example using everything you learned:

import { useState } from 'react';

// 1. Props type
type ProfileCardProps = {
  initialName: string;
};

// 2. Component with typed props
const ProfileCard: React.FC<ProfileCardProps> =
  ({ initialName }) => {

  // 3. Typed state
  const [name, setName] =
    useState<string>(initialName);

  const [isEditing, setIsEditing] =
    useState<boolean>(false);

  return (
    <div>
      {isEditing ? (
        <input
          value={name}
          onChange={(e) =>
            setName(e.target.value)}
        />
      ) : (
        <h2>{name}</h2>
      )}
      <button onClick={() =>
        setIsEditing(!isEditing)}>
        {isEditing ? "Save" : "Edit"}
      </button>
    </div>
  );
};

🎉 What You Learned

graph TD A["TypeScript Basics"] --> B["Setup"] A --> C["Typing Components"] A --> D["Typing Props"] A --> E["Typing State"] B --> F[".tsx files + tsconfig.json"] C --> G["React.FC type"] D --> H["type Props + optional ?"] E --> I["useState with generics"]
Topic Key Takeaway
Setup Use .tsx files and tsconfig.json
Components Type with React.FC
Props Create a type and pass it to component
State Use useState<Type>(initial)

🚀 You’re Ready!

TypeScript might feel like extra work at first. But think about it:

  • Without labels: You might put socks in the fridge
  • With labels: Everything goes where it belongs

TypeScript is your labeling friend. It catches mistakes BEFORE they become bugs. Now go build something amazing! 🎯

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.