#typescript #cheatsheet
A strongly-typed superset of JavaScript. TypeScript adds static typing, modern JS features, and great tooling for large-scale applications.
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42]; // Fixed-type array
enum Color { Red = "RED", Green = "GREEN" };
let notSure: any = "could be anything";
let nothing: void = undefined; // Used for function returns
interface User {
id: number;
name: string;
email?: string; // Optional
}
const user: User = { id: 1, name: "Alice" };
function add(a: number, b: number): number {
return a + b;
}
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
// Async/await
async function fetchData(): Promise<Data> {
const response = await fetch('/api');
return response.json();
}
class Person {
private age: number;
constructor(public name: string, age: number) {
this.age = age;
}
describe(): string {
return `${this.name} is ${this.age} years old.`;
}
}
class Employee extends Person {
constructor(name: string, age: number, public role: string) {
super(name, age);
}
}
function identity<T>(arg: T): T {
return arg;
}
interface ApiResponse<T> {
data: T;
status: number;
}
const response: ApiResponse<User> = { data: user, status: 200 };
type StringOrNumber = string | number; // Union
type Combined = User & { permissions: string[] }; // Intersection
if (typeof value === "string") { /* ... */ }
if (value instanceof User) { /* ... */ }
// Custom type guard
function isString(x: unknown): x is string {
return typeof x === 'string';
}
// Type Aliases
type Point = { x: number; y: number };
// Utility Types
type PartialUser = Partial<User>;
type NameOnly = Pick<User, 'name'>;
type PermissionMap = Record<string, boolean>;
type ReadonlyUser = Readonly<User>;
// Structural Typing (Duck Typing)
interface A { name: string }
const obj = { name: 'test', extra: true };
const a: A = obj; // OK
import { Route } from '@/types';
import got from '@/utils/got';
import { getApiUrl, parseArticle } from './common';
async function handler(ctx): Promise<Output> {
const data = await got({ method: 'get', url: '/api' });
return process(data);
}
// Parallel async
const items = await Promise.all([fn1(), fn2()]);
const apiUrl = new URL('/endpoint', 'https://example.com');
apiUrl.searchParams.append('key', 'value');
const { data } = response;
const attributes = item.attributes;
async function handler(ctx: Context): Promise<Output> { /*...*/ }
tsc file.ts # Compiles to file.js
Project config:
{
"compilerOptions": {
"target": "ES6",
"strict": true
}
}
import got from 'got';
interface Article {
id: number;
title: string;
}
async function fetchArticles(): Promise<Article[]> {
const url = new URL('/articles', 'https://example.com');
url.searchParams.append('sort', '-date');
const response = await got({ method: 'get', url: url.toString() });
return response.body.data;
}