DEV Community

Cover image for TypeScript Cheat Sheet: Essential Tips for JavaScript Developers
Bryan N. Lomerio
Bryan N. Lomerio

Posted on

TypeScript Cheat Sheet: Essential Tips for JavaScript Developers

  1. Basic Types
let isDone: boolean = false;
let count: number = 42;
let name: string = 'Bryan Lomerio';
Enter fullscreen mode Exit fullscreen mode
  1. Arrays
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob', 'Charlie'];
Enter fullscreen mode Exit fullscreen mode
  1. Tuples
let user: [string, number] = ['Bryan', 25];
Enter fullscreen mode Exit fullscreen mode
  1. *Enums *
enum Role {
  Admin = 'admin',
  User = 'user',
  Guest = 'guest',
}

let currentRole: Role = Role.Admin;
Enter fullscreen mode Exit fullscreen mode
  1. Any Type
let uncertain: any = 42;
uncertain = 'Now a string';
uncertain = true;
Enter fullscreen mode Exit fullscreen mode
  1. Void (Function with No Return)
function logMessage(message: string): void {
  console.log(message);
}
Enter fullscreen mode Exit fullscreen mode
  1. Null and Undefined
let n: null = null;
let u: undefined = undefined;
Enter fullscreen mode Exit fullscreen mode
  1. Type Aliases
type ID = string | number;
let userId: ID = 'abc123';
userId = 42;
Enter fullscreen mode Exit fullscreen mode
  1. Interfaces
interface Person {
  name: string;
  age: number;
}

let user: Person = { name: 'Alice', age: 30 };

10. **Functions**

function add(x: number, y: number): number {
  return x + y;
}

const subtract = (x: number, y: number): number => x - y;
Enter fullscreen mode Exit fullscreen mode
  1. Classes
class Person {
  name: string;
  age: number;

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

  greet(): void {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

let person = new Person('Bryan', 25);
person.greet();
Enter fullscreen mode Exit fullscreen mode
  1. Generics
function identity<T>(value: T): T {
  return value;
}

let stringIdentity = identity<string>('Hello');
let numberIdentity = identity<number>(42);

13. **Type Assertions**

let someValue: any = 'Hello, TypeScript!';
let strLength: number = (someValue as string).length;
Enter fullscreen mode Exit fullscreen mode
  1. Union Types
function printId(id: string | number): void {
  console.log(id);
}

printId('abc123');
printId(100);
Enter fullscreen mode Exit fullscreen mode
  1. Type Narrowing
function printInfo(value: string | number) {
  if (typeof value === 'string') {
    console.log(`String: ${value}`);
  } else {
    console.log(`Number: ${value}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)