more-tips
Here are the 10 key points from the video with corresponding TypeScript code examples for each point:
TypeScript Configuration for React: To use React with TypeScript, ensure you have the necessary type definitions installed (
@types/react
and@types/react-dom
). In thetsconfig.json
, thejsx
option should be set topreserve
for Next.js or appropriate settings for React Native.{
"compilerOptions": {
"jsx": "preserve"
}
}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>;
};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 }[];
};Functions in Props: Ensure functions passed as props have typed arguments for better autocomplete and validation.
type MyComponentProps = {
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
};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;
};useState and TypeScript: Always provide a type argument to
useState
to define the type of state.const [user, setUser] = useState<User | undefined>(undefined);
useRef and TypeScript: Specify the type for
useRef
and provide a default value to avoid undefined types.const myRef = useRef<HTMLDivElement>(null);
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;
}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 };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.