10 TypeScript Tips Every React Developer Should Know

•3 min read•
#typescript#react#javascript#tips

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:

tsx
// ❌ Too verbose
const [count, setCount] = useState<number>(0);
// ✅ Let TypeScript infer
const [count, setCount] = useState(0);

2. Proper Props Typing

Use type for props, it's more flexible than interface:

tsx
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:

tsx
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:

tsx
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:

tsx
// Pick specific props
type UserPreview = Pick<User, 'id' | 'name' | 'avatar'>;
// Omit props you don't need
type UserWithoutPassword = Omit<User, 'password'>;
// Make all optional
type PartialUser = Partial<User>;
// Make all required
type RequiredUser = Required<User>;
// Extract union member
type Status = 'idle' | 'loading' | 'success';
type ActiveStatus = Exclude<Status, 'idle'>; // 'loading' | 'success'

6. Type-Safe Event Handlers

Properly type your event handlers:

tsx
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:

tsx
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:

tsx
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:

tsx
function useToggle(initial = false): [boolean, () => void] {
const [value, setValue] = useState(initial);
const toggle = () => setValue(v => !v);
return [value, toggle];
}
// Usage
const [isOpen, toggleOpen] = useToggle();

10. Strict Mode Configuration

Enable strict TypeScript settings in tsconfig.json:

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:

tsx
// ❌ Unsafe
function process(data: any) {
return data.value; // No error, even if data.value doesn't exist
}
// ✅ Safe
function 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.