Typescript Cheatsheet
JS
R
JavaScriptTypescript cheatsheet covering most of the subset keys
1============================================================
2# 01/2025 UPDATE
3// Type-checks values while preserving literal types
4// satisfies - ensures color values are RGB while keeping literal types
5const theme = {
6 primary: '#FF0000',
7 secondary: '#00FF00'
8} satisfies Record<string, `#${string}`>
9
10// Automatic resource cleanup (like Python's 'with' or Java's try-with-resources)
11using file = await fs.open('log.txt');
12await file.write('hello'); // auto-closes when scope ends
13
14// Top-level async operations without wrapping in async function
15const data = await fetch('api/users');
16export const users = await data.json();
17
18// Immutable data structures with hash syntax (similar to Ruby symbols)
19const coords = #[23.4, 45.6];
20coords[0] = 25; // Error: Cannot modify
21const copy = coords.with(0, 25); // Creates new tuple
22
23// Structured pattern matching (similar to Rust/Scala)
24const response = match (status) {
25 when (200) => 'OK',
26 when (404) => 'Not Found',
27 when (n if n >= 500) => 'Server Error',
28 when (_) => 'Unknown'
29}
30
31===============================================================================================
32TYPES
33
34// Use interface when:
35✓ You're defining object shapes/APIs
36✓ You want declaration merging
37✓ You're working in an OOP style
38interface UserAPI {
39 name: string;
40 login(): void;
41}
42
43// Use type when:
44✓ You need unions/intersections
45✓ You're working with functions/tuples
46✓ You need mapped/utility types
47type Status = 'active' | 'inactive';
48type Handler = (event: Event) => void;
49
50>>>>>>
51
52// Interface: extendable, mergeable, better DX
53// Type: unions/intersections, primitives, more flexible
54// Class: includes runtime implementation
55// Enum: named constants with runtime object
56
57// Interface - extendable, better for OOP
58interface User {
59 name: string;
60}
61interface User { // Can be merged
62 age: number;
63}
64// Result in this single interface
65interface User {
66 name: string;
67 age: number;
68}
69
70
71// Type - more flexible, better for unions/intersections
72type Animal = {
73 species: string;
74}
75type Pet = Animal & { // Cannot be merged, but can be combined
76 name: string;
77}
78
79// Class - adds runtime behavior
80class Employee {
81 constructor(public role: string) {}
82 work() {}
83}
84
85// Enum - named constants
86enum Status {
87 Active,
88 Inactive
89}
90
91
92
93===============================================================================================
942021 UPDATE
95
96// Branded Types (assign different ‘labels’ to values, it's like validation boundaries)
97type Password = Brand<string, 'Password'>;
98const takesInPassword = (password: Password) => {}
99takesInPassword(‘4123123’) // error
100takesInPassword(‘4123123’ as Password) // OK
101
102// Globals (type functions and variables directly in the global scope)
103declare global { function myFunc(): boolean; var myVar: number; }
104console.log(myVar); console.log(myFunc());
105
106readonly VAPID_PUBLIC_KEY = 'xxx';
107
108// Tsconfig (comnpilerOptions)
109// "strict": true, // All strict flags are turned on
110// "strictNullChecks": true, // Null checks for nullable types
111
112
113// Ensure that all child objects have a specific structure from interface MessageAttributeValue
114type MessageBodyAttributeMap = {[key: string]: MessageAttributeValue};
115interface MessageAttributeValue {
116 StringValue?: String;
117 BinaryValue?: Binary;
118 StringListValues?: StringList;
119 BinaryListValues?: BinaryList;
120 DataType: String;
121 }
122
123// Types vs Interfaces
124- type aliases can act sort of like interfaces, however, there are 3 important differences ( union types, declaration merging)
125- use whatever suites you and your team, just be consistent
126- always use interface for public API's definition when authoring a library or 3rd party ambient type definitions
127- consider using type for your React Component Props and StateCreated on 6/25/2018