Dec 19 2024 ~ 4 min read

Typescript for React Devs



TypeScript for React with Next.js Cheatsheet

I recently started working with Next.js and TypeScript, and I’ve put together a quick cheatsheet to share. This way, we can use this post as a handy reference whenever we need a reminder about the details we might forget.

1. Basic TypeScript Types

  • string: Represents text.
    let name: string = "John";
  • number: Represents numbers.
    let age: number = 30;
  • boolean: Represents true/false.
    let isAdmin: boolean = true;
  • any: Disables type checking for a variable (use sparingly).
    let anything: any = 123;

2. Arrays & Objects

  • Typed Array:
    let numbers: number[] = [1, 2, 3];
  • Typed Object:
    type User = { name: string; age: number };
    let user: User = { name: "Alice", age: 25 };

3. Functions

  • Typing Function Parameters and Return Values:
    function add(a: number, b: number): number {
      return a + b;
    }
  • Arrow Function:
    const greet = (name: string): string => `Hello, ${name}`;

4. React Component Props

  • Functional Component Props:
    type ButtonProps = { label: string; onClick: () => void };
    
    const Button: React.FC<ButtonProps> = ({ label, onClick }) => (
      <button onClick={onClick}>{label}</button>
    );

5. React Component State

  • With useState Hook:
    const [count, setCount] = React.useState<number>(0);

6. Optional and Default Props

  • Optional Props (?):
    type CardProps = { title: string; description?: string };
    const Card: React.FC<CardProps> = ({ title, description }) => (
      <div>
        <h1>{title}</h1>
        <p>{description || "No description available"}</p>
      </div>
    );
  • Default Props:
    const Card = ({ title, description = "Default description" }: CardProps) => { ... };

7. TypeScript with useEffect

  • Adding Type to Effect Dependencies:
    React.useEffect(() => {
      console.log("Hello TypeScript");
    }, []); // Dependencies must also follow the types

8. Next.js Specifics

  • getStaticProps:
    export const getStaticProps: GetStaticProps = async () => {
      return { props: { message: "Hello" } };
    };
  • getServerSideProps:
    export const getServerSideProps: GetServerSideProps = async (context) => {
      return { props: { data: "Server data" } };
    };
  • Custom App Component:
    import type { AppProps } from "next/app";
    
    const MyApp = ({ Component, pageProps }: AppProps) => (
      <Component {...pageProps} />
    );
    
    export default MyApp;

9. Types for API Requests

  • API Handler Type:
    import type { NextApiRequest, NextApiResponse } from "next";
    
    export default function handler(req: NextApiRequest, res: NextApiResponse) {
      res.status(200).json({ message: "Hello API" });
    }

10. Utility Types

  • Partial: Makes all properties optional.
    type User = { name: string; age: number };
    const partialUser: Partial<User> = { name: "John" };
  • Pick: Select specific properties from a type.
    type User = { name: string; age: number; admin: boolean };
    type UserName = Pick<User, "name">;
  • Omit: Exclude specific properties.
    type UserWithoutAdmin = Omit<User, "admin">;

11. keyof and Index Types

  • keyof: Create a union of object keys.
    type User = { name: string; age: number };
    type UserKeys = keyof User; // "name" | "age"

12. Type Assertions

  • When you are sure about a type:
    const myElement = document.getElementById("app") as HTMLDivElement;

13. TypeScript in JSX

  • Event Types:
    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
      console.log(event.target);
    };

14. Extending Types

  • Extending Props:
    type BaseProps = { id: string };
    type ExtendedProps = BaseProps & { name: string };
    
    const Component: React.FC<ExtendedProps> = ({ id, name }) => (
      <div>{id}: {name}</div>
    );

15. Generic Components

  • Reusable Components:
    type ListProps<T> = { items: T[] };
    
    const List = <T,>({ items }: ListProps<T>) => (
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    );

Headshot of Alvaro Uribe

Hi, I'm Alvaro. I'm a software engineer from Chile 🇨🇱 based in New Zealand 🇳🇿.