gofmt for one canonical stylego build, go test, modules, race detector


amd64, arm64, 386, arm, riscv64, wasm …GOOS=none -> soon™go tool dist listGOOS=js GOARCH=wasm (browser)GOOS=wasip1 GOARCH=wasm (WASI)

go build / go run / go install / go testgo test, go fmt, go vet, go generatego mod + go.sum go doc & pkg.go.dev go tool (pprof, trace, dist) 

go f()-race detector 

net/http encoding/json, crypto, io, time, os, regexp ...testing 



implements keywordundefined



> true == 1
true
> true === 1
false
> typeof null
'object'
> [] == ![]
true
> [] + []
''
> [1, 2, 3] + [1]
'1,2,31'


// TypeScript source code (.ts)
function greet(name: string): string {
return `Hello, ${name}!`;
}
let user: string = "Alice";
let age: number = 30;// Compiled JavaScript (.js)
function greet(name) {
return `Hello, ${name}!`;
}
let user = "Alice";
let age = 30;
type Person = {
name: string;
age: number;
}
interface Employee {
name: string;
age: number;
}
function introduce(person: Person) {
console.log(`${person.name}, ${person.age}`);
}
const alice: Person = { name: "Alice", age: 30 };
const bob: Employee = { name: "Bob", age: 25 };
const charlie = { name: "Charlie", age: 35, department: "Engineering" }; // Extra property
introduce(alice); // ✅ Works (exact Person)
introduce(bob); // ✅ Works (Employee has same shape)
introduce(charlie); // ✅ Works (has name + age, extra is fine)
const david = { name: "David" }; // missing 'age'
introduce(david); // ❌ Error: Property 'age' is missing
let name = "Alice"; // inferred: string
let age = 30; // inferred: number
let isActive = true; // inferred: boolean
let items = [1, 2, 3]; // inferred: number[]
let result = name + age; // inferred: string (number gets coerced)
function multiply(a: number, b: number) {
return a * b; // inferred return type: number
}
const users = ["Alice", "Bob", "Charlie"];
users.forEach((user) => {
console.log(user.toUpperCase()); // ✅ TypeScript knows user has .toUpperCase()
});
let mixed = [1, "hello", true]; // inferred: (string | number | boolean)[]
let something; // inferred: any (avoid this!)
something = "hello";
something = 42; // No error, but 'any' disables type checking
// 1. GENERIC FUNCTION
function identity<T>(value: T): T {
return value;
}
// 2. GENERIC INTERFACE
interface Box<T> {
value: T;
getValue(): T;
setValue(value: T): void;
}
// 3. GENERIC CLASS
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
}
// 4. MULTIPLE TYPE PARAMETERS
function pair<A, B>(first: A, second: B): [A, B] {
return [first, second];
}
// 5. GENERIC CONSTRAINT
interface HasLength { length: number; }
function logLength<T extends HasLength>(item: T): T {
console.log(item.length);
return item;
}
// 6. GENERIC DEFAULT TYPE
interface ApiResponse<T = any> {
data: T;
status: number;
}
// 7. GENERIC TYPE ALIAS
type Result<T, E = Error> =
{ success: true; value: T } |
{ success: false; error: E };
// Step 1: Start with plain JS (existing code)
// user.js
function getUserData(id) {
return fetch(`/api/users/${id}`)
.then(response => response.json())
.then(data => {
return {
id: data.id,
name: data.name,
email: data.email
};
});
}
function displayUser(user) {
console.log(`${user.name} (${user.email})`);
}
let userId = 123;
getUserData(userId).then(displayUser);// Step 3: Gradually add types
// (file-by-file, function-by-function)
// user.ts - with types
interface User {
id: number;
name: string;
email: string;
}
// Add return type annotation
function getUserData(id: number): Promise<User> {
return fetch(`/api/users/${id}`)
.then(response => response.json())
.then(data => {
return {
id: data.id,
name: data.name,
email: data.email
};
});
}
// Add parameter type
function displayUser(user: User): void {
console.log(`${user.name} (${user.email})`);
}
let userId: number = 123; // Type added
getUserData(userId).then(displayUser);// Step 2: Rename to .ts - it STILL works
// user.ts - same code, no changes needed!
function getUserData(id) {
return fetch(`/api/users/${id}`)
.then(response => response.json())
.then(data => {
return {
id: data.id,
name: data.name,
email: data.email
};
});
}
function displayUser(user) {
console.log(`${user.name} (${user.email})`);
}
let userId = 123;
getUserData(userId).then(displayUser);
// ✅ COMPILES! TypeScript didn't complain
// Union: Can be either
type Status = "loading" | "success" | "error";
let current: Status = "loading"; // ✅
current = "success"; // ✅
current = "failed"; // ❌ Error
// Intersection: Combines everything
type Person = { name: string };
type Employee = { id: number };
type Worker = Person & Employee; // { name: string; id: number }
// Optional: May not exist
interface Config {
timeout?: number; // Can be omitted
}
interface Product {
id: number;
name: string;
price: number;
}
// keyof - all property names
type ProductKeys = keyof Product; // "id" | "name" | "price"
// typeof - capture runtime value's type
const config = { port: 3000, host: "localhost" };
type ConfigType = typeof config; // { port: number; host: string }
// Indexed access - property type
type PriceType = Product["price"]; // number
// Nested indexed access
type Nested = { a: { b: { c: string } } };
type CType = Nested["a"]["b"]["c"]; // string
// Conditional type (type-level if)
type Awaited<T> = T extends Promise<infer U> ? U : T;
type A = Awaited<Promise<string>>; // string
type B = Awaited<number>; // number
// Mapped type (transform each property)
type Nullable<T> = { [P in keyof T]: T[P] | null };
interface User { id: number; name: string; }
type NullableUser = Nullable<User>; // { id: number | null; name: string | null }
// Built-in mapped types (utility types)
type ReadonlyUser = Readonly<User>; // { readonly id: number; readonly name: string }
type PartialUser = Partial<User>; // { id?: number; name?: string }
type PickUser = Pick<User, "id">; // { id: number }
// Infer (extract return type)
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Type can also describe a function
function greet(): string { return "hello"; }
type Result = GetReturnType<typeof greet>; // string
// Real-world: Type-safe event system
type EventMap = {
click: { x: number; y: number };
keypress: { key: string; ctrlKey: boolean };
focus: { target: Element };
};
// Extract event names as union type
type EventName = keyof EventMap; // "click" | "keypress" | "focus"
// Generic event handler type using indexed access
type EventHandler<T extends EventName> = (data: EventMap[T]) => void;
// Make all event handlers optional using mapped + utility types
type EventHandlers = {
[E in EventName]?: EventHandler<E>;
};
// Usage
const handlers: EventHandlers = {
click: (data) => console.log(data.x, data.y),
// keypress is optional
};

import fs from 'fs';
fs.readFile('config.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
console.log('This runs before file is read');
// Callback hell example
fs.readFile('a.json', 'utf8', (err, a) => {
fs.readFile('b.json', 'utf8', (err, b) => {
fs.readFile('c.json', 'utf8', (err, c) => {
// pyramid of doom
});
});
});import fs from 'fs/promises';
async function readConfig() {
try {
const data = await fs.readFile('config.json', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readConfig();
console.log('This runs before file is read');
// Sequential reads, clean and flat
async function readAll() {
try {
const a = await fs.readFile('a.json', 'utf8');
const b = await fs.readFile('b.json', 'utf8');
const c = await fs.readFile('c.json', 'utf8');
console.log(a, b, c);
} catch (err) {
console.error(err);
}
}import fs from 'fs/promises';
fs.readFile('config.json', 'utf8')
.then((data) => {
console.log('File content:', data);
})
.catch((err) => {
console.error('Error reading file:', err);
});
console.log('This runs before file is read');
// Chaining instead of nesting
fs.readFile('a.json', 'utf8')
.then((a) => fs.readFile('b.json', 'utf8'))
.then((b) => fs.readFile('c.json', 'utf8'))
.then((c) => console.log(c))
.catch((err) => console.error(err));| Callback (Node.js original style) | Promise with .then() (ES2015) | Async/Await (ES2017) |
|---|

| Worker threads | Web Workers | Cluster | Child process | |
|---|---|---|---|---|
| Environment | Node.js | Browser | Node.js | Node.js |
| Unit | Thread | Thread | Process | Process |
| Shared memory | opt-in | opt-in | ❌ | ❌ |
| Use case | CPU-bound tasks | Keep UI responsive | Scale HTTP servers | External tools |
| Crash isolation | ❌ | ❌ | ✅ | ✅ |


| Runtime | Engine | Environments |
|---|---|---|
| Node.js | V8 | Server, CLI, desktop |
| Deno | V8 | Server, CLI, edge |
| Bun | JavaScriptCore (Nitro) | Server, CLI |
| Browser(s) | V8 / SpiderMonkey / JavaScriptCore | Client |
| Cloudflare workers | V8 | Edge / CDN nodes |
| Vercel Edge | V8 | Edge / CDN nodes |
| Electron | V8 + Chromium | Desktop apps |
| React Native | Hermes / JSCore | iOS, Android |
| Espruino | Custom | Microcontrollers |
| Kaluma | JerryScript | Microcontrollers |







| Capability | Node.js | Deno | Browser |
|---|---|---|---|
| File system | fs | Deno.readFile | ❌ |
| HTTP server | http | Deno.serve | ❌ |
| HTTP client | fetch | fetch | fetch |
| Environment vars | process.env | process.env | ❌ |
| DOM / UI | ❌ | ❌ | document, window |
| Graphics | ❌ | ❌ | Canvas, WebGL, WebGPU |

{
"name": "my-library",
"version": "1.0.1",
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"typescript": "^5.0.0"
},
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}





package main
import "fmt"
func main() {
fmt.Println("Hello from Go")
}const msg: string = "Hello from TypeScript";
console.log(msg);

package main
import "fmt"
func main() {
fmt.Println("Hello from Go")
}const msg: string = "Hello from TypeScript";
console.log(msg);

| Runtime | Build command | Build time | Exec (avg/10) | Binary size |
|---|---|---|---|---|
| Go | go build | 150 ms | 1.8 ms | 2.3 MB |
| Go (run) | go run (compile+run) | - | 158 ms | no artifact |
| Bun | bun build --compile | 272 ms | 15 ms | 91 MB |
| Deno | deno compile | 573 ms | 30 ms | 90 MB |
| Node SEA | --experimental-sea + postject | ~4830 ms | 23 ms | 124 MB |
| Node | node app.ts (no build) | - | 60 ms | needs runtime |

package main
import "fmt"
func main() {
// type error
var n int = "not a number"
fmt.Println(n)
}// type error
let n: number = "not a number";
console.log(n);

package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
fmt.Println("worker", n, "done")
}(i)
}
wg.Wait()
fmt.Println("all done")
}const work = (n: number): Promise<string> =>
new Promise(res =>
setTimeout(() => {
console.log(`worker ${n} done`);
res();
})
)
const main = async () => {
await Promise.all([1, 2, 3].map(work));
console.log("all done");
};
main();

package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
in := []byte(`{"name":"Ada","age":36}`)
var u User
json.Unmarshal(in, &u)
out, _ := json.Marshal(u)
fmt.Println(u.Name, u.Age)
fmt.Println(string(out))
}interface User {
name: string;
age: number;
}
const input = '{"name":"Ada","age":36}';
const u: User = JSON.parse(input);
console.log(u.name, u.age);
console.log(JSON.stringify(u));

package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("not-a-number")
if err != nil {
fmt.Println("handled error:", err)
return
}
fmt.Println("parsed:", n)
}function parse(s: string): number {
const n = Number(s);
if (Number.isNaN(n)) {
throw new Error(`cannot parse: ${s}`);
}
return n;
}
try {
console.log("parsed:", parse("not-a-number"));
} catch (e) {
console.log("handled error:", (e as Error).message);
}

package main
import "fmt"
type User struct{ Name string }
func find(id int) *User {
if id == 1 {
return &User{Name: "Ada"}
}
return nil // nothing found
}
func main() {
u := find(2)
if u == nil {
fmt.Println("no user (nil check)")
return
}
fmt.Println(u.Name)
}interface User { name: string; }
function find(id: number): User | undefined {
return id === 1 ? { name: "Ada" } : undefined;
}
const u = find(2);
// optional chaining + nullish coalescing
console.log(u?.name ?? "no user (undefined check)");

package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r http.Request) {
fmt.Fprintln(w, "Hello from Go (net/http, stdlib)")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:8099", nil)
}import { createServer } from "http";
const srv = createServer((_req, res) => {
res.end("Hello from Node (http, stdlib)\n");
});
srv.listen(8098, "localhost");


