10 TypeScript Tips Every React Developer Should Know
Level up your React TypeScript skills with these practical tips for better type safety and developer experience.
TypeScript has become the standard for React development, but many developers don't use it to its full potential. Here are 10 practical tips that will make you more productive.
1. Use Type Inference
Don't over-annotate. TypeScript is smart:
// ❌ Too verboseconst [count, setCount] = useState<number>(0);
// ✅ Let TypeScript inferconst [count, setCount] = useState(0);2. Proper Props Typing
Use type for props, it's more flexible than interface:
type ButtonProps = { variant: 'primary' | 'secondary'; children: React.ReactNode; onClick?: () => void;};
export function Button({ variant, children, onClick }: ButtonProps) { return <button onClick={onClick}>{children}</button>;}3. Generic Components
Make reusable components with generics:
type SelectProps<T> = { options: T[]; value: T; onChange: (value: T) => void; renderOption: (option: T) => React.ReactNode;};
function Select<T>({ options, value, onChange, renderOption }: SelectProps<T>) { // Component logic}4. Discriminated Unions for State
Handle different states type-safely:
type State = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: User[] } | { status: 'error'; error: string };
function UserList({ state }: { state: State }) { if (state.status === 'loading') return <Spinner />; if (state.status === 'error') return <Error message={state.error} />; if (state.status === 'success') return <List users={state.data} />; return null;}5. Utility Types are Your Friends
Learn these essential utility types:
// Pick specific propstype UserPreview = Pick<User, 'id' | 'name' | 'avatar'>;
// Omit props you don't needtype UserWithoutPassword = Omit<User, 'password'>;
// Make all optionaltype PartialUser = Partial<User>;
// Make all requiredtype RequiredUser = Required<User>;
// Extract union membertype Status = 'idle' | 'loading' | 'success';type ActiveStatus = Exclude<Status, 'idle'>; // 'loading' | 'success'6. Type-Safe Event Handlers
Properly type your event handlers:
function Form() { const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); // TypeScript knows e.currentTarget is HTMLFormElement };
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { console.log(e.target.value); // Type-safe };
return ( <form onSubmit={handleSubmit}> <input onChange={handleChange} /> </form> );}7. Ref Typing
Properly type refs for DOM elements:
function Input() { const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => { inputRef.current?.focus(); // Safe optional chaining }, []);
return <input ref={inputRef} />;}8. As Const for Literal Types
Create readonly literal types:
const COLORS = { primary: '#6366f1', secondary: '#8b5cf6',} as const;
type Color = typeof COLORS[keyof typeof COLORS];// Color = '#6366f1' | '#8b5cf6'9. Custom Hook Typing
Return tuple types from hooks:
function useToggle(initial = false): [boolean, () => void] { const [value, setValue] = useState(initial); const toggle = () => setValue(v => !v); return [value, toggle];}
// Usageconst [isOpen, toggleOpen] = useToggle();10. Strict Mode Configuration
Enable strict TypeScript settings in tsconfig.json:
{ "compilerOptions": { "strict": true, "noUncheckedIndexedAccess": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true }}Bonus: Avoid 'any'
When you don't know the type, use unknown instead of any:
// ❌ Unsafefunction process(data: any) { return data.value; // No error, even if data.value doesn't exist}
// ✅ Safefunction process(data: unknown) { if (typeof data === 'object' && data !== null && 'value' in data) { return (data as { value: string }).value; }}Conclusion
TypeScript isn't just about adding types - it's about making your code more maintainable and catching bugs before they reach production. These tips will help you write better, safer React code.
Pro tip: Use the TypeScript playground to experiment and learn. The more you practice, the more natural it becomes.