TypeScript for App Code
Add static types to your React Native code to catch bugs early and make props, state and API responses self-documenting.
Beginner · about 8 hours · difficulty 2/5
Learn first: JavaScript Essentials
TypeScript is JavaScript with a type checker. Expo templates use it by default, and most professional React Native codebases are written in it. Types catch typos, wrong props and unhandled undefined values before the app ever runs on a phone.
Core concepts
- Annotations and inference:
let count: number, but let the compiler infer where it can. - Object shapes with
typeorinterface, optional fields (name?: string). - Union types such as
"idle" | "loading" | "error"model screen states cleanly. - Generics like
Array<T>andPromise<T>describe containers and async results. - Narrowing with
if,typeofand discriminated unions.
In a React Native app
- Type component props:
function Avatar({ uri, size }: { uri: string; size: number }). - Type API responses so the rest of the app knows what data looks like. Remember types vanish at runtime; validate untrusted network data (for example with Zod) if correctness matters.
- Type navigation params so a screen cannot be opened without required arguments.
Pitfalls
Sprinkling any silences the compiler and removes the benefit. Prefer unknown and narrow it.
Good enough to move on: you can type a component's props, a fetch result and a union of UI states without reaching for any.
Key concepts
- Type annotations and inference
- Types vs interfaces
- Union and literal types
- Generics
- Narrowing and discriminated unions
- Typing React components and props
- Runtime validation with Zod
Mini project
Convert your expenses script to TypeScript with strict mode on, modelling each expense and a union type for its category.
Check yourself
If your API type says a field is always a string but the server sometimes sends null, why won't TypeScript save you, and what can?
Free resources
- TypeScript Handbook (TypeScript)
- Using TypeScript with React Native (React Native)