Skip to content

Typescript Cheatheet

Published: at 12:00 PM

TypeScript is a powerful superset of JavaScript that brings static typing, better tooling, and a cleaner codebase. In this guide, we’ll walk you through the basics of TypeScript, from installation to integrating it with React, designed especially for newcomers and developers familiar with languages like Java or C.


Table of Contents

Open Table of Contents

Why TypeScript?

TypeScript offers several advantages over plain JavaScript:

If you’re transitioning from Java or C, you’ll appreciate its type safety and object-oriented features.


Getting Started

Installation

Install TypeScript globally:

npm install -g typescript

Verify the installation:

tsc --version

Setting Up a React Project

To create a React project with TypeScript, run:

npx create-react-app my-app --template typescript

Navigate to your project:

cd my-app

Start the development server:

npm start

Basic Syntax

Variables

TypeScript introduces explicit type annotations.

let message: string = "Hello, TypeScript!";
let age: number = 25;
let isActive: boolean = true;

// Type inference
let greeting = "Hi there!"; // Inferred as a string

Branching (If-Else)

let score: number = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else {
  console.log("Grade: C");
}

Looping

const items: string[] = ["Apple", "Banana", "Cherry"];

// For loop
for (let i = 0; i < items.length; i++) {
  console.log(items[i]);
}

// For-of loop
for (const item of items) {
  console.log(item);
}

// While loop
let i: number = 0;
while (i < items.length) {
  console.log(items[i]);
  i++;
}

Arrays

const numbers: number[] = [1, 2, 3];
numbers.push(4);

// Tuple
const user: [string, number] = ["Alice", 30];
console.log(user[0]); // Alice
console.log(user[1]); // 30

Object-Oriented Programming

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): string {
    return `Hello, I am ${this.name}, aged ${this.age}.`;
  }
}

const person = new Person("John", 28);
console.log(person.greet());

Using TypeScript with React

Functional Components

Create a simple Greeting component with props.

import React from "react";

interface GreetingProps {
  name: string;
}

const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

export default Greeting;

State and Props with Hooks

import React, { useState } from "react";

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

Typing Events

const InputField: React.FC = () => {
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    console.log(event.target.value);
  };

  return <input type="text" onChange={handleChange} />;
};

Context API

import React, { createContext, useContext, useState } from "react";

interface AuthContextType {
  isLoggedIn: boolean;
  login: () => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | null>(null);

const AuthProvider: React.FC = ({ children }) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn,
        login: () => setIsLoggedIn(true),
        logout: () => setIsLoggedIn(false),
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

const AuthStatus: React.FC = () => {
  const auth = useContext(AuthContext);

  if (!auth) return null;

  return auth.isLoggedIn ? (
    <button onClick={auth.logout}>Logout</button>
  ) : (
    <button onClick={auth.login}>Login</button>
  );
};

export const App = () => (
  <AuthProvider>
    <AuthStatus />
  </AuthProvider>
);

Conclusion

TypeScript offers a robust development experience, especially when paired with React. Its static typing and enhanced tooling improve code quality and reduce runtime errors. Follow this guide to get started and elevate your front-end development with TypeScript.

Ready to build your next project? Dive into TypeScript today!
Explore TypeScript


Previous Post
Understanding React Higher-Order Components (HOCs)
Next Post
Adding LaTeX Equations in AstroPaper blog posts