Skip to main content

more-tips

Here are the 10 key points from the video with corresponding TypeScript code examples for each point:

  1. TypeScript Configuration for React: To use React with TypeScript, ensure you have the necessary type definitions installed (@types/react and @types/react-dom). In the tsconfig.json, the jsx option should be set to preserve for Next.js or appropriate settings for React Native.

    {
    "compilerOptions": {
    "jsx": "preserve"
    }
    }
  2. Typing Props: Define types for props using interfaces or types. This allows for strong typing of component props.

    type MyComponentProps = {
    name: string;
    };

    const MyComponent: React.FC<MyComponentProps> = ({ name }) => {
    return <div>{name}</div>;
    };
  3. Optional Props and Arrays: You can define optional props using the ? syntax and type arrays of objects for props.

    type MyComponentProps = {
    items?: { id: number; name: string }[];
    };
  4. Functions in Props: Ensure functions passed as props have typed arguments for better autocomplete and validation.

    type MyComponentProps = {
    onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
    };
  5. Children in Props: Use React.ReactNode to type children props, and make them required or optional based on your needs.

    type MyComponentProps = {
    children: React.ReactNode;
    };
  6. useState and TypeScript: Always provide a type argument to useState to define the type of state.

    const [user, setUser] = useState<User | undefined>(undefined);
  7. useRef and TypeScript: Specify the type for useRef and provide a default value to avoid undefined types.

    const myRef = useRef<HTMLDivElement>(null);
  8. Creating Custom Hooks: Mark the return type of custom hooks as const to have TypeScript infer a tuple type instead of an array type.

    function useMyHook() {
    const [state, setState] = useState(0);
    return [state, setState] as const;
    }
  9. Discriminated Unions in Props: Use discriminated unions to create props types that depend on other props, ensuring type safety based on conditions.

    type ModalProps =
    | { type: 'alert'; message: string }
    | { type: 'confirm'; message: string; confirmButtonMessage: string };
  10. Generic Components: Create generic components to pass dynamic types to props, allowing for more flexible and reusable components.

    type TableProps<T> = {
    data: T[];
    onRowClick: (row: T) => void;
    };

    function Table<T>(props: TableProps<T>) {
    // component logic
    }

These points cover the essentials of using TypeScript with React, including how to type props, state, refs, and children, as well as creating custom hooks and using advanced types like discriminated unions and generics for dynamic and reusable components.