TypeScript Scripting Basics

TypeScript is JavaScript with types. React Native uses TypeScript, so you need the basics.

Running TypeScript

You need Node.js installed. Then install tsx (TypeScript Execute) to run .ts files:

npm install -g tsx
tsx script.ts

Variables

let name: string = "Alice";        // Cannot change type
const age: number = 25;            // Cannot reassign at all
let isStudent: boolean = true;
let hobbies: string[] = ["reading", "coding"];

Key rule: const = cannot reassign. let = can reassign. Prefer const.

Type Inference

You don't always need to write the type — TypeScript figures it out:

let name = "Alice";     // TypeScript knows this is a string
let age = 25;           // TypeScript knows this is a number

Functions

// Named function
function greet(name: string): string {
    return `Hello, ${name}!`;
}

// Arrow function (preferred in React)
const greet = (name: string): string => {
    return `Hello, ${name}!`;
};

// One-liner
const greet = (name: string): string => `Hello, ${name}!`;

console.log(greet("Alice"));  // Hello, Alice!

Interfaces (Defining Object Shapes)

interface Person {
    name: string;
    age: number;
    city?: string;       // ? means optional
}

const alice: Person = {
    name: "Alice",
    age: 25
};

Arrays and Array Methods

const numbers: number[] = [1, 2, 3, 4, 5];

// map — transform each element
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// filter — keep elements that match
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]

// find — get first match
const firstEven = numbers.find(n => n % 2 === 0);
// 2

// reduce — combine into one value
const sum = numbers.reduce((total, n) => total + n, 0);
// 15

Async/Await

async function fetchData(): Promise<string> {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    return data;
}

// Arrow function version
const fetchData = async (): Promise<string> => {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    return data;
};

Error Handling

async function safeFetch(url: string): Promise<any> {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error("Fetch failed:", error);
        return null;
    }
}

Working with JSON

// Parse JSON string to object
const jsonString = '{"name": "Alice", "age": 25}';
const person = JSON.parse(jsonString);
console.log(person.name);  // Alice

// Convert object to JSON string
const backToJson = JSON.stringify(person);
console.log(backToJson);   // {"name":"Alice","age":25}

Console Logging

console.log("Simple message");
console.log("Value:", someVariable);
console.error("Error message");   // Red text in terminal
console.warn("Warning");          // Yellow text in terminal

Your Turn — Mini Script

Create fetch-example.ts:

interface Todo {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
}

async function fetchTodos(): Promise<Todo[]> {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos");
    const todos: Todo[] = await response.json();
    return todos.slice(0, 5);
}

async function main() {
    const todos = await fetchTodos();
    todos.forEach(todo => {
        console.log(`[${todo.completed ? "✓" : " "}] ${todo.title}`);
    });
}

main().catch(console.error);

Run it:

tsx fetch-example.ts