DEV Community

Cover image for Typescript Cheatsheet — Essential Syntax and Concepts
Parthiban
Parthiban

Posted on

Typescript Cheatsheet — Essential Syntax and Concepts

Introduction

TypeScript is a powerful superset of JavaScript that adds static typing and enhanced features to the language. It provides developers with the ability to write more robust and scalable code. However, with its added features and syntax, it can sometimes be overwhelming to keep track of all the details. In this blog, we'll provide you with a TypeScript cheatsheet containing essential syntax and concepts to help you write cleaner and more maintainable code.


Types:

TypeScript introduces static types, allowing you to explicitly define the type of variables, parameters, and function return values. Here are some commonly used types:

let variable: string;
let count: number;
let isTrue: boolean;
let list: Array<number>;
let tuple: [string, number];
let anyValue: any;
let voidValue: void;
Enter fullscreen mode Exit fullscreen mode

Variables and Constants:

TypeScript supports declaring variables and constants using the let and const keywords, similar to JavaScript. You can also explicitly specify the type:

let variableName: string = "Hello";
const constantName: number = 42;

let inferredVariable = "World"; // Inferred as string
Enter fullscreen mode Exit fullscreen mode

Functions:

Functions in TypeScript can have explicit type annotations for parameters and return values. Arrow functions provide a concise syntax. Optional parameters can be specified using the ? symbol:

function functionName(parameter: string): number {
  return parameter.length;
}

const arrowFunction = (parameter: string): number => parameter.length;

function optionalParams(param1: string, param2?: number): void {
  // Function body
}
Enter fullscreen mode Exit fullscreen mode

Interfaces and Classes:

Interfaces and classes help define contracts and provide structure to your code. Here's an example of an interface and a class:

interface Person {
  name: string;
  age: number;
}

class Student implements Person {
  name: string;
  age: number;

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

  sayHello(): void {
    console.log(`Hello, my name is ${this.name}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Generics:

Generics allow you to create reusable components that work with different types. They provide flexibility and type safety. Here's how generics can be used in TypeScript:

function genericFunction<T>(arg: T): T {
  return arg;
}

class GenericClass<T> {
  private data: T[];

  constructor() {
    this.data = [];
  }

  addItem(item: T): void {
    this.data.push(item);
  }

  getItem(index: number): T {
    return this.data[index];
  }
}
Enter fullscreen mode Exit fullscreen mode

Modules:

TypeScript supports modules, allowing you to organize your code into reusable and manageable units. You can export and import functions, variables, and classes:

export function functionName() { ... }
export const variableName = 42;

import { functionName, variableName } from './module';
Enter fullscreen mode Exit fullscreen mode

Type Assertions:

Type assertions allow you to tell the compiler about the type of a value when it can't be inferred automatically. It's useful when working with dynamic data:

let someValue: any = "Hello, World!";
let stringLength: number = (someValue as string).length;
Enter fullscreen mode Exit fullscreen mode

Type Guards:

Type guards help narrow down the type of a variable within a conditional block. They're particularly useful when working with union types:

function processValue(value: string | number): void {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else {
    console.log(value.toFixed(2));
  }
}
Enter fullscreen mode Exit fullscreen mode

Enums:

Enums provide a way to define a set of named constants, representing a set of possible values. They can make your code more readable and expressive:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

let dir: Direction = Direction.Up;
Enter fullscreen mode Exit fullscreen mode

Error Handling:

TypeScript supports standard error handling mechanisms like try-catch-finally blocks, allowing you to handle and recover from exceptions:

try {
  // Code that may throw an error
} catch (error) {
  // Handle the error
} finally {
  // Code that always executes
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

This TypeScript cheatsheet provides a quick reference to essential syntax and concepts, empowering you to write more reliable and maintainable code. Remember, TypeScript offers many more features and capabilities than covered here, so be sure to explore the official TypeScript documentation to further enhance your TypeScript skills.

Happy coding! ❤️

Top comments (0)