React Native is written in JavaScript, and in this course in TypeScript, which is JavaScript with types. You do not need to master the language first. You need a working set of ideas that appear in every app. This lesson teaches them with small programs. To run them, create a file such as demo.ts in any folder and run npx tsx demo.ts, or paste the code into the online TypeScript Playground.
Variables and types
Use const for values that are never reassigned and let for values that change. Avoid the old var. TypeScript infers most types from the value, and you add a type where it is not obvious, mainly on function parameters and on objects that other code uses. Backticks make template strings, where ${...} inserts a value.
const name: string = "Asha";
let steps = 5000;
const goal = 10000;
steps += 1500;
const percent = Math.round((steps / goal) * 100);
console.log(`${name} walked ${steps} steps`);
console.log(`That is ${percent}% of the goal`);
Asha walked 6500 steps
That is 65% of the goal
Functions, arrays and types
Arrow functions are short functions. Array methods are the main tool for working with lists: filter keeps items, map changes every item, reduce folds them into one value. They return new arrays and do not change the old one. In React you always create new arrays and objects instead of changing existing ones, because React compares them to decide what to redraw. A type describes the shape of an object, and ? marks an optional field.
type User = { name: string; age?: number };
function greet(user: User, greeting = "Hello"): string {
return `${greeting}, ${user.name}!`;
}
const double = (n: number) => n * 2;
const scores = [40, 75, 90, 55];
const passed = scores.filter((s) => s >= 50);
const doubled = passed.map(double);
const total = scores.reduce((sum, s) => sum + s, 0);
console.log(greet({ name: "Ravi" }));
console.log(greet({ name: "Ravi" }, "Welcome"));
console.log(passed);
console.log(doubled);
console.log(total);
Hello, Ravi!
Welcome, Ravi!
[ 75, 90, 55 ]
[ 150, 180, 110 ]
260
Destructuring and spread
Destructuring pulls values out of objects and arrays into variables. The spread operator ... copies an object or array and lets you change part of it. You will use { ...item, done: true } constantly to update state.
const person = { name: "Meera", city: "Pune", skills: ["React", "TypeScript"] };
const { name, city } = person;
const [first, ...others] = person.skills;
const updated = { ...person, city: "Delhi" };
console.log(name, city);
console.log(first, others);
console.log(updated.city, person.city);
Meera Pune
React [ 'TypeScript' ]
Delhi Pune
Async code
Network calls and storage take time, so they return a Promise: a value that arrives later. async functions use await to wait for a promise while the rest of the app keeps running. Put the awaited code in try/catch to handle errors.
const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function loadUser(id: number): Promise<{ id: number; name: string }> {
await wait(100);
if (id < 0) throw new Error("Bad id");
return { id, name: `User ${id}` };
}
async function main() {
try {
const user = await loadUser(7);
console.log(user.name);
await loadUser(-1);
} catch (e) {
console.log("Failed:", (e as Error).message);
}
}
main();
User 7
Failed: Bad id
Why this matters in React Native
- State updates use spread and
mapto build new objects and lists. - Every API call, database call and permission request is async.
- Types catch mistakes such as passing a number where text is expected, before you run the app.
- Optional fields and
?.stop crashes when data is missing.
Your task
- Run all four samples and compare the output.
- Write a type
Productwith name and price, a list of three products and print the names of those above 100. - Write an async function that waits 200 ms and returns a number, call it and print the result.
- Use destructuring to read
cityfrom an object that may not have it, with a default value.
How to check it worked
- Your outputs match the lesson.
- You can explain why React code copies arrays instead of changing them.
- You know what
awaitdoes and where to puttry/catch.