Logo

dev-resources.site

for different kinds of informations.

Typescript quick concept refresher and reference

Published at
9/25/2024
Categories
webdev
typescript
cheatsheet
programming
Author
keshav___dev
Author
12 person written this
keshav___dev
open
Typescript quick concept refresher and reference

TypeScript is a powerful superset of JavaScript that adds static types, making your code more robust and maintainable. Whether you're a beginner or an experienced developer, having a cheat sheet can be incredibly handy. This post provides a comprehensive cheat sheet to help you quickly reference key TypeScript concepts and syntax.

Basic Types

  • any: A type that can be anything.
  let variable: any;
Enter fullscreen mode Exit fullscreen mode
  • boolean: True or false values.
  let isDone: boolean = false;
Enter fullscreen mode Exit fullscreen mode
  • number: All numbers, including integers and floats.
  let decimal: number = 6;
Enter fullscreen mode Exit fullscreen mode
  • string: Textual data.
  let color: string = "blue";
Enter fullscreen mode Exit fullscreen mode
  • array: Arrays of a specific type.
  let list: number[] = [1, 2, 3];
  let list: Array<number> = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode
  • tuple: An array with a fixed number of elements of specific types.
  let x: [string, number];
  x = ["hello", 10];
Enter fullscreen mode Exit fullscreen mode
  • enum: A way to define a set of named constants.
  enum Color {Red, Green, Blue}
  let c: Color = Color.Green;
Enter fullscreen mode Exit fullscreen mode
  • void: The absence of any type, commonly used for functions that do not return a value.
  function warnUser(): void {
    console.log("This is my warning message");
  }
Enter fullscreen mode Exit fullscreen mode
  • null and undefined: Their own types as well as subtypes of all other types.
  let u: undefined = undefined;
  let n: null = null;
Enter fullscreen mode Exit fullscreen mode

Advanced Types

  • union: A variable that can hold multiple types.
  let value: string | number;
  value = "hello";
  value = 42;
Enter fullscreen mode Exit fullscreen mode
  • type alias: Creating a new name for a type.
  type Name = string;
  type NameOrNumber = Name | number;
Enter fullscreen mode Exit fullscreen mode
  • interface: Describes the shape of an object.
  interface Person {
    firstName: string;
    lastName: string;
  }
  let user: Person = { firstName: "John", lastName: "Doe" };
Enter fullscreen mode Exit fullscreen mode
  • type assertion: Telling the compiler to treat a variable as a different type.
  let someValue: any = "this is a string";
  let strLength: number = (someValue as string).length;
Enter fullscreen mode Exit fullscreen mode

Functions

  • Function Types: Describing the types of functions.
  function add(x: number, y: number): number {
    return x + y;
  }
  let myAdd: (x: number, y: number) => number = function(x, y) { return x + y; };
Enter fullscreen mode Exit fullscreen mode
  • Optional and Default Parameters: Parameters that are optional or have default values.
  function buildName(firstName: string, lastName?: string): string {
    return firstName + " " + (lastName || "");
  }
Enter fullscreen mode Exit fullscreen mode

Classes

  • Basic Class: Defining a class with properties and methods.
  class Greeter {
    greeting: string;
    constructor(message: string) {
      this.greeting = message;
    }
    greet() {
      return "Hello, " + this.greeting;
    }
  }
  let greeter = new Greeter("world");
Enter fullscreen mode Exit fullscreen mode
  • Inheritance: Extending a class to create a new class.
  class Animal {
    move(distanceInMeters: number = 0) {
      console.log(`Animal moved ${distanceInMeters}m.`);
    }
  }
  class Dog extends Animal {
    bark() {
      console.log("Woof! Woof!");
    }
  }
  let dog = new Dog();
  dog.bark();
  dog.move(10);
Enter fullscreen mode Exit fullscreen mode

Generics

  • Generic Functions: Functions that work with any data type.
  function identity<T>(arg: T): T {
    return arg;
  }
  let output = identity<string>("myString");
Enter fullscreen mode Exit fullscreen mode
  • Generic Classes: Classes that work with any data type.
  class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
  }
  let myGenericNumber = new GenericNumber<number>();
  myGenericNumber.zeroValue = 0;
  myGenericNumber.add = function(x, y) { return x + y; };
Enter fullscreen mode Exit fullscreen mode

Utility Types

  • Partial: Makes all properties in a type optional.
  interface Todo {
    title: string;
    description: string;
  }
  function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
    return { ...todo, ...fieldsToUpdate };
  }
Enter fullscreen mode Exit fullscreen mode
  • Readonly: Makes all properties in a type read-only.
  interface Todo {
    title: string;
  }
  const todo: Readonly<Todo> = {
    title: "Delete inactive users"
  };
Enter fullscreen mode Exit fullscreen mode

Conclusion

This cheat sheet covers the essentials of TypeScript, providing a quick reference for common types, functions, classes, and more. Keep it handy as you work on your TypeScript projects to streamline your development process and ensure you're using the language to its full potential.

cheatsheet Article's
30 articles in total
Favicon
Vim cheat sheet
Favicon
The Ultimate Cheat Sheet: CLI Man Pages, tldr, and cheat.sh
Favicon
From FZF file preview to a browser for cht.sh to discovering the ideal solution
Favicon
Seaborn Cheat Sheet
Favicon
SQL Quick Reference: Simplifying Database Management
Favicon
Terraform Commands Cheat Sheet
Favicon
JavaScript Interview Cheat Sheet - Part 1
Favicon
JavaScript Interview Cheat Sheet - Part 2
Favicon
Arch Linux Pacman: A Detailed Guide with Commands and Examples 🎩🐧
Favicon
The Art of AI Conversation: 6 Essential Tips for Chat LLM Success
Favicon
Master CSS Selectors
Favicon
End-to-End Flexbox vs. Grid vs. Traditional.
Favicon
Linux Commands Cheat Sheet :)
Favicon
sql joins: moving in together
Favicon
A Yocto Cheatsheet
Favicon
Typescript quick concept refresher and reference
Favicon
cheat sheet for go mod package management
Favicon
Git para Iniciantes: Tudo o que vocΓͺ precisa saber para comeΓ§ar a usar
Favicon
Git Commands You Need for Hacktoberfest 2024 - Git cheat sheet
Favicon
Git Cheatsheet that will make you a master in Git
Favicon
How to learn HTML: 46 great sites, courses and books (all free)
Favicon
Top 5 Cheat sheets for Developers
Favicon
CSS: List of Properties for Text
Favicon
What's in a name?
Favicon
The HTML History and Optimization Cheat Sheet
Favicon
Kubernetes Cheat Sheet: Essential Commands for Beginners
Favicon
🦊 GitLab Cheatsheet - 16 - CICD Catalog
Favicon
πŸ“ SQL Cheat Sheet for Developers
Favicon
The Ultimate SQL JOIN Cheat Sheet
Favicon
JavaScript Cheat Sheets

Featured ones: