Basic Types
TypeScript offers several primitive types that you can use to type your variables. Let's explore the most important ones.
Primitive Types
String
For text, use the string type:
typescript
let name: string = "Pedro";let greeting: string = `Hello, ${name}!`;let phrase: string = 'Using single quotes also works';Number
For numbers (integers and decimals), use number:
typescript
let age: number = 30;let price: number = 99.99;let hex: number = 0xf00d;let binary: number = 0b1010;Boolean
For true/false values:
typescript
let active: boolean = true;let loggedIn: boolean = false;Arrays
There are two ways to type arrays:
typescript
// Method 1: type[]let numbers: number[] = [1, 2, 3, 4, 5];let names: string[] = ["Ana", "Bruno", "Carlos"]; // Method 2: Array<type>let values: Array<number> = [10, 20, 30];Tuples
Tuples are arrays with fixed types and size:
typescript
// [string, number] - exactly in this orderlet person: [string, number] = ["Pedro", 30]; // Accessing elementsconsole.log(person[0]); // "Pedro"console.log(person[1]); // 30 // Error: wrong type in positionperson = [30, "Pedro"]; // Error!Enum
Enums allow you to define a set of named constants:
typescript
enum Status { Pending, // 0 Processing, // 1 Completed, // 2 Error // 3} let orderStatus: Status = Status.Processing; // With custom valuesenum HttpStatus { OK = 200, NotFound = 404, ServerError = 500}Any and Unknown
Any
The any type disables type checking. Use sparingly!
typescript
let anything: any = "text";anything = 42; // OKanything = true; // OKanything.foo(); // OK (but may error at runtime!)Unknown
unknown is a safer alternative to any:
typescript
let value: unknown = "text"; // Error: cannot use directlyconsole.log(value.length); // Error! // Must check the type firstif (typeof value === "string") { console.log(value.length); // OK!}Void, Null and Undefined
typescript
// void - for functions that don't return anythingfunction logMessage(msg: string): void { console.log(msg);} // null and undefinedlet nothing: null = null;let notDefined: undefined = undefined; // With strictNullChecks, you must be explicitlet maybeString: string | null = null;maybeString = "now it's a string";Never
The never type represents values that never occur:
typescript
// Function that never returnsfunction throwError(message: string): never { throw new Error(message);} // Infinite loopfunction infiniteLoop(): never { while (true) {}}Type Inference
TypeScript can infer types automatically:
typescript
// TypeScript infers that 'name' is stringlet name = "Pedro"; // TypeScript infers that 'numbers' is number[]let numbers = [1, 2, 3]; // TypeScript infers the return type as numberfunction double(n: number) { return n * 2;}Conclusion
These basic types are the foundation of TypeScript. In the next lesson, we'll see how to create custom types with interfaces and type aliases.