Simple Interfaces
Interfaces are used to describe the shape of an object. They act as a contract for what properties an object should have.
interface User {id: number;username: string;}const user: User = {id: 1,username: "alex"};
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.
Interfaces are used to describe the shape of an object. They act as a contract for what properties an object should have.
interface User {id: number;username: string;}const user: User = {id: 1,username: "alex"};
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.
let count: number = 10;let message: string = "Hello TypeScript";let isActive: boolean = true;
In TypeScript, you can define the types of the parameters a function receives and the type of the value it returns.
function greet(name: string): string {return "Hello, " + name;}
TypeScript allows you to define arrays that contain only a specific type of element, preventing accidental mixed-type arrays.
const fruits: string[] = ["Apple", "Banana"];const scores: Array<number> = [95, 88, 100];
Union types allow a variable to be one of several types. This is useful when a value could legitimately be different types.
let result: string | number;result = "Success";result = 200;
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.
const user = { details: { name: 'Bob' } };const name = user?.details?.name;
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.
const settings = { volume: 0 };const volume = settings.volume ?? 50;
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.
const rawData: any = '123';const dataLength = (rawData as string).length;