TypeScript for React Native
Why we use it and how it prevents bugs
TypeScript Essentials
TypeScript is JavaScript with Types. It catches bugs while you type, instead of when your user crashes the app.
Why TypeScript?
Without types:
function greet(user) {
return "Hello, " + user.nmae; // Typos happen! Result: "Hello, undefined"
}With types:
interface User {
name: string;
}
function greet(user: User) {
return "Hello, " + user.nmae; // ❌ Error: Property 'nmae' does not exist on type 'User'.
}Real World Example: Auth Types
Located at src/features/auth/types/index.ts. We use Zod for runtime validation and TypeScript interfaces for static checking.
1. Interfaces (The Shape of Data)
We define what a User looks like across the entire app.
// src/features/auth/types/index.ts
export interface User {
id: string;
email: string;
name: string;
avatar?: string; // Optional property (can be undefined)
createdAt: string;
}2. Props (Component Arguments)
Every React component expects specific "Props".
// src/ui/components/Button.tsx
interface ButtonProps {
label: string; // Required
onPress: () => void; // Function
variant?: 'primary' | 'secondary'; // Union type (only specific strings allowed)
isLoading?: boolean; // Optional boolean
}
const Button = ({ label, variant = 'primary' }: ButtonProps) => { ... }3. Generics (Reusable Types)
Generics allow us to create flexible components/functions that work with any type. Think of them as "arguments for types".
// RTK Query example
// builder.query<ResultType, ArgumentType>
builder.query<User, string>({
queryFn: (id) => getUser(id)
});This tells TypeScript: "This query accepts a string (id) and returns a User.
TS Cheat Sheet for React Native
Primitives
let isDone: boolean = false;
let lines: number = 42;
let name: string = "Anders";Arrays
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3]; // Same thingFunctions
function add(x: number, y: number): number {
return x + y;
}Optional & Union
interface Props {
id?: string; // string or undefined
status: 'active' | 'inactive'; // Union
}[!TIP] Learning Strategy: Don't try to learn all of TypeScript at once. Focus on Interfaces and Props. The more complex generic types (
Record,Partial,Pick) will come naturally as you need them.