blog thumnail

TypeScript Cheat Sheet: Essential Concepts and Features

typescript

Tanveer Sayem / 2023-07-10

5 min read

TypeScript is a powerful superset of JavaScript that adds static typing and advanced features to the language. It provides a type system that helps catch errors and improve code quality during development. This cheat sheet covers some of the essential concepts and features of TypeScript to help you write more reliable and maintainable code.

Declaring Variables and Types

Declare variables with explicit types using the let or const keyword:
let num: number = 10;
const message: string = 'Hello, TypeScript!';
TypeScript supports various primitive types such as number, string, boolean, and any. You can also declare custom types using interfaces, enums, or type aliases.

Type Annotations and Inference

TypeScript provides type inference, which infers the type based on the assigned value:
let num = 10; // inferred as number
const message = 'Hello, TypeScript!'; // inferred as string
You can also provide explicit type annotations to override type inference:
let num: number = 10;
const message: string = 'Hello, TypeScript!';
Type annotations are especially useful when the initial value doesn't determine the type or when you want to enforce specific types.

Functions and Parameters

Declare functions with parameter types and return types:
function add(num1: number, num2: number): number {
  return num1 + num2;
}
You can use optional parameters and default values:
function greet(name: string, age?: number = 18): void {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

Interfaces

Use interfaces to define object structures and enforce consistency:
interface Person {
  name: string;
  age: number;
}
function greet(person: Person): void {
  console.log(`Hello, ${person.name}! You are ${person.age} years old.`);
}
Interfaces can also describe function types, class structures, and more.

Classes and Inheritance

Create classes with properties and methods:
class Animal {
  constructor(public name: string) {}
  move(distance: number): void {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}
class Dog extends Animal {
  bark(): void {
    console.log('Woof! Woof!');
  }
}
const dog = new Dog('Buddy');
dog.move(10);
dog.bark();
TypeScript supports inheritance, access modifiers (public, private, protected), and more advanced class features.

Generics

Use generics to create reusable components that work with different types:
function identity<T>(value: T): T {
  return value;
}
const num: number = identity(10);
const message: string = identity('Hello, TypeScript!');
Generics allow you to write flexible and type-safe code, enabling abstraction and reusability.

Modules

Organize your code into modules for better encapsulation and maintainability:
// math.ts
export function add(num1: number, num2: number): number {
  return num1 + num2;
}
// app.ts
import { add } from './math';
console.log(add(5, 3)); // Outputs: 8
Modules allow you to split your code into separate files and control their visibility and accessibility.

Compiler Configuration (tsconfig.json)

Customize the behavior of the TypeScript compiler by configuring `tsconfig.json`:
{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "outDir": "dist",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}
The `compilerOptions` section allows you to specify the target ECMAScript version, module system, output directory, strictness, and many other options.

Conclusion

This TypeScript cheat sheet covers some of the essential concepts and features to help you write more reliable and maintainable code. TypeScript's static typing, interfaces, classes, and other advanced features enable you to catch errors early in the development process and improve the overall quality of your JavaScript applications. So, keep this cheat sheet handy and leverage the power of TypeScript in your projects. Happy coding!
---
Feel free to refer to this cheat sheet whenever you need a quick reference for TypeScript concepts and features. Happy coding!
If you click on my affiliates links and shop(anything, not just books), I am going to receive a tiny commission. AND… Most of the time, you will receive an offer. Win/Win! The products that I have are the ones I believe in.
amazon

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.


  • Home
  • About
  • Newsletter
  • Twitter
  • Github
  • YouTube
  • Setup
  • Guestbook
  • Snippets