0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
TypeScript · BeginnerSnippet

Simple Interfaces

Interfaces are used to describe the shape of an object. They act as a contract for what properties an object should have.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
interface User {
id: number;
username: string;
}
const user: User = {
id: 1,
username: "alex"
};
SyntaxBest Practices
TypeScript · BeginnerSnippet

Type Annotations

Type annotations allow us to explicitly specify the type of a variable. This helps the compiler catch errors if we try to assign a value of the wrong type.

snippet.ts
typescript
1
2
3
let count: number = 10;
let message: string = "Hello TypeScript";
let isActive: boolean = true;
SyntaxData Types
TypeScript · BeginnerSnippet

Basic Function Types

In TypeScript, you can define the types of the parameters a function receives and the type of the value it returns.

snippet.ts
typescript
1
2
3
function greet(name: string): string {
return "Hello, " + name;
}
FunctionsSyntax
TypeScript · BeginnerSnippet

Defining Arrays

TypeScript allows you to define arrays that contain only a specific type of element, preventing accidental mixed-type arrays.

snippet.ts
typescript
1
2
const fruits: string[] = ["Apple", "Banana"];
const scores: Array<number> = [95, 88, 100];
Arrays & ListsData Types
TypeScript · BeginnerSnippet

Union Types

Union types allow a variable to be one of several types. This is useful when a value could legitimately be different types.

snippet.ts
typescript
1
2
3
let result: string | number;
result = "Success";
result = 200;
Data TypesSyntax
TypeScript · BeginnerSnippet

Optional Chaining

The optional chaining operator (?.) permits reading the value of a property deep within a chain of objects without having to check if each reference is valid.

snippet.ts
typescript
1
2
const user = { details: { name: 'Bob' } };
const name = user?.details?.name;
SyntaxBest Practices
TypeScript · BeginnerSnippet

Nullish Coalescing

The nullish coalescing operator (??) returns its right-hand operand when its left-hand operand is null or undefined. Unlike ||, it treats 0 as a valid value.

snippet.ts
typescript
1
2
const settings = { volume: 0 };
const volume = settings.volume ?? 50;
SyntaxControl Flow
TypeScript · BeginnerSnippet

Type Assertions

Type assertions are a way to tell the compiler to treat a value as a specific type when you have more information about it than TypeScript does.

snippet.ts
typescript
1
2
const rawData: any = '123';
const dataLength = (rawData as string).length;
Syntax