In TypeScript, types are a way to describe the shape of a value, telling us what kind of data it holds. This helps catch errors during development, making your code more robust and easier to maintain. TypeScript offers a rich set of built-in types, and you can also create your own.
These are the most basic types of data.
let message: string = "Hello, TypeScript!";let age: number = 30;
let price: number = 19.99;let isDone: boolean = false;let currentName: string | null = null;let undeclaredVariable: undefined;const id = Symbol('user_id');
let userId: symbol = id;let veryLargeNumber: bigint = 123456789012345678901234567890n;These represent more complex data structures.
let dynamicValue: any = 42;
dynamicValue = "Now I'm a string!"; let userObject: object = { name: "Alice", age: 25 };function logMessage(message: string): void {
console.log(message);
}function throwError(message: string): never {
throw new Error(message);
}let status: "pending" | "success" | "error" = "pending";
status = "success"; interface Draggable {
drag(): void;
}
interface Resizable {
resize(): void;
}
type UIWidget = Draggable & Resizable;
let textBox: UIWidget = {
drag: () => { },
resize: () => { }
};TypeScript has a powerful feature called type inference. If you do not explicitly provide a type annotation, TypeScript will try to infer the type based on the value assigned.
let greeting = "Hello"; Understanding these types is fundamental to writing effective TypeScript code. You can combine them to create complex and type-safe applications.