TypeScript Cheat Sheet: Essential Tips for JavaScript Developers
Basic Types
let isDone: boolean = false;
let count: number = 42;
let name: string = 'Bryan Lomerio';
Arrays
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob', 'Charlie'];
Tuples
let user: [string, number] = ['Bryan', 25];
*Enums
*
enum Role {
Admin = 'admin',
User = 'user',
Guest = 'guest',
}
let currentRole: Role = Role.Admin;
Any Type
let uncertain: any = 42;
uncertain = 'Now a string';
uncertain = true;
Void (Function with No Return)
function logMessage(message: string): void {
console.log(message);
}
Null and Undefined
let n: null = null;
let u: undefined = undefined;
Type Aliases
type ID = string | number;
let userId: ID = 'abc123';
userId = 42;
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;
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();
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;
Top comments (0)